In [1]:
import pandas as pd
import zipfile
pd.set_option("display.max_columns" , None)
import warnings
warnings.filterwarnings('ignore')
import seaborn as sns
from sklearn.impute import KNNImputer
from sklearn.model_selection import StratifiedKFold
import random
import os
import numpy as np
from lightgbm import LGBMRegressor
from lazypredict.Supervised import LazyClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, roc_auc_score, confusion_matrix, classification_report, roc_curve, auc
from lightgbm import LGBMClassifier
import numpy as np
import matplotlib.pyplot as plt
import plotly.graph_objects as go
import numpy as np
from sklearn.linear_model import RidgeClassifierCV
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler
import optuna
from sklearn.model_selection import StratifiedKFold
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier , ExtraTreesClassifier
from xgboost import XGBClassifier
from sklearn.naive_bayes import GaussianNB
import time
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.ensemble import AdaBoostClassifier

from catboost import CatBoostClassifier
from sklearn.model_selection import RepeatedStratifiedKFold
import random
import os
import numpy as np
import optuna
from sklearn.calibration import CalibratedClassifierCV
In [2]:
def seed_all(SEED=42):
    random.seed(SEED)

    np.random.seed(SEED)
    os.environ['PYTHONHASHSEED'] = str(SEED)
    

seed_all()
In [3]:
np.random.seed(42)
In [4]:
zip_file_path = "widsdatathon2024-challenge1.zip"
with zipfile.ZipFile(zip_file_path , 'r') as zip_ref : 
    zip_ref.extractall()
In [5]:
train = pd.read_csv('training.csv')
test = pd.read_csv('test.csv')
sub = pd.read_csv('sample_submission.csv')
In [6]:
train.head()
Out[6]:
patient_id patient_race payer_type patient_state patient_zip3 patient_age patient_gender bmi breast_cancer_diagnosis_code breast_cancer_diagnosis_desc metastatic_cancer_diagnosis_code metastatic_first_novel_treatment metastatic_first_novel_treatment_type Region Division population density age_median age_under_10 age_10_to_19 age_20s age_30s age_40s age_50s age_60s age_70s age_over_80 male female married divorced never_married widowed family_size family_dual_income income_household_median income_household_under_5 income_household_5_to_10 income_household_10_to_15 income_household_15_to_20 income_household_20_to_25 income_household_25_to_35 income_household_35_to_50 income_household_50_to_75 income_household_75_to_100 income_household_100_to_150 income_household_150_over income_household_six_figure income_individual_median home_ownership housing_units home_value rent_median rent_burden education_less_highschool education_highschool education_some_college education_bachelors education_graduate education_college_or_above education_stem_degree labor_force_participation unemployment_rate self_employed farmer race_white race_black race_asian race_native race_pacific race_other race_multiple hispanic disabled poverty limited_english commute_time health_uninsured veteran Ozone PM25 N02 DiagPeriodL90D
0 475714 NaN MEDICAID CA 924 84 F NaN C50919 Malignant neoplasm of unsp site of unspecified... C7989 NaN NaN West Pacific 31437.75 1189.56 30.64 16.01 15.54 17.61 14.01 11.61 11.56 7.57 4.00 2.10 49.86 50.14 36.57 11.89 47.11 4.44 3.93 52.23 52996.29 3.14 4.00 6.16 5.14 6.27 10.14 13.30 20.00 12.74 11.57 7.53 19.10 24563.57 44.59 8674.50 264634.29 1165.00 37.44 33.26 29.20 25.91 8.36 3.26 11.61 39.56 61.53 8.47 13.43 0.00 44.10 13.10 5.10 1.49 0.34 27.11 8.76 66.69 12.87 22.54 10.10 27.81 11.20 3.50 52.24 8.65 18.61 1
1 349367 White COMMERCIAL CA 928 62 F 28.49 C50411 Malig neoplm of upper-outer quadrant of right ... C773 NaN NaN West Pacific 39121.88 2295.94 38.20 11.88 13.35 14.23 13.42 13.33 14.06 10.25 5.95 3.50 49.89 50.11 50.25 9.83 35.29 4.65 3.62 61.74 102741.64 2.33 1.54 2.65 2.18 2.41 5.16 7.97 13.94 12.47 19.76 29.60 49.36 41287.27 61.46 11725.67 677688.52 2003.12 34.75 14.23 19.99 29.80 23.74 12.25 35.98 47.92 65.23 5.10 15.22 0.03 54.03 2.53 20.83 0.59 0.30 11.65 10.08 37.95 8.96 10.11 8.06 30.61 7.02 4.10 42.30 8.49 20.11 1
2 138632 White COMMERCIAL TX 760 43 F 38.09 C50112 Malignant neoplasm of central portion of left ... C773 NaN NaN South West South Central 21996.68 626.24 37.91 13.03 14.46 12.53 13.54 12.86 12.77 11.43 6.57 2.81 50.12 49.88 55.75 12.33 27.20 4.71 3.26 55.80 85984.74 2.48 1.30 2.72 2.94 2.77 6.76 12.06 15.84 13.56 20.88 18.68 39.55 40399.03 72.75 7786.58 237713.05 1235.91 29.36 10.81 27.04 32.37 19.68 10.12 29.79 37.31 66.43 4.56 13.72 3.65 75.82 9.23 3.62 0.46 0.15 3.82 6.90 19.37 11.25 9.66 3.36 31.39 15.07 7.45 40.11 7.64 14.84 1
3 617843 White COMMERCIAL CA 926 45 F NaN C50212 Malig neoplasm of upper-inner quadrant of left... C773 NaN NaN West Pacific 32795.33 1896.22 42.87 10.07 12.14 12.54 12.46 12.65 14.85 12.28 8.22 4.76 49.07 50.93 52.60 11.62 31.14 4.62 3.10 54.56 120533.83 3.44 1.27 2.18 2.21 2.10 4.38 5.89 10.90 10.72 18.85 38.06 56.91 55336.29 59.22 12171.30 1012474.22 2354.74 32.03 5.84 12.15 26.27 33.29 22.46 55.75 48.94 64.43 5.26 18.50 0.05 65.01 1.44 18.85 0.43 0.25 5.43 8.61 16.72 8.85 8.69 5.28 27.56 4.40 4.81 42.07 7.23 15.89 0
4 817482 NaN COMMERCIAL ID 836 55 F NaN 1749 Malignant neoplasm of breast (female), unspeci... C773 NaN NaN West Mountain 10886.26 116.89 43.47 10.82 13.98 9.49 10.36 12.60 14.99 14.84 9.46 3.47 52.31 47.69 57.88 14.96 21.76 5.41 3.35 47.21 61075.13 2.59 1.96 3.17 3.24 4.78 11.46 15.66 22.43 12.48 13.62 8.61 22.23 29073.18 77.10 3768.06 249845.72 919.74 27.03 11.58 29.59 39.17 13.98 5.68 19.66 42.33 57.49 4.26 13.03 6.89 86.71 0.43 0.66 0.76 0.11 5.08 6.26 13.33 15.28 11.22 1.95 26.17 12.09 13.11 41.36 4.11 11.72 0
In [7]:
train[train["metastatic_first_novel_treatment_type"].notna()].DiagPeriodL90D.value_counts()
Out[7]:
1    16
0     8
Name: DiagPeriodL90D, dtype: int64
In [8]:
# correlation_matrix = train.corr()

# # Set up the matplotlib figure
# plt.figure(figsize=(50, 30))

# # Create a heatmap using Seaborn to visualize the correlation matrix
# heatmap = sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt=".2f")

# # Show the plot
# plt.show()
In [9]:
# heatmap.get_figure().savefig('correlation_matrix.png', bbox_inches='tight')

# # Show the plot
# plt.show()
In [10]:
train = train.drop(9336)
In [11]:
def check_nan(df):
    for i,j in  enumerate(df.isna().sum()) : 
        print(f'{df.isna().sum().index[i]} ==> {j}')
In [12]:
train['male_1'] = train['male']
test['male_1'] = test['male']

train['female_1'] = train['female']
test['female_1'] = test['female']

train.drop(['male' , 'female'] , axis = 1 , inplace =True)
test.drop(['male' , 'female'] , axis = 1 , inplace =True)
In [13]:
def custom_tokenizer(text):
    # Split the text into words
    words = text.split()
    # Include non-contiguous sequences (e.g., "upper-left" as a single token)
    tokens = [word if "-" not in word else f'"{word}"' for word in words]
    return tokens
In [14]:
map_words = {"Malig " :"Malignant " ,  " ovrlp ":" overlapping " , " neoplm " : " neoplasm " , '(female)' : 'female' , " unsp " : " unspecified " , " sites " : " site " ," breast, "  :" breast " ," areola, " : " areola " , "female," : "female"  }

def replace_words(text):
    for old_word, new_word in map_words.items():
        text = text.replace(old_word, new_word)
    return text

train['breast_cancer_diagnosis_desc'] = train['breast_cancer_diagnosis_desc'].apply(replace_words)
test['breast_cancer_diagnosis_desc'] = test['breast_cancer_diagnosis_desc'].apply(replace_words)
In [15]:
train['breast_cancer_diagnosis_desc'] .unique()
Out[15]:
array(['Malignant neoplasm of unspecified site of unspecified female breast',
       'Malignant neoplasm of upper-outer quadrant of right female breast',
       'Malignant neoplasm of central portion of left female breast',
       'Malignant neoplasm of upper-inner quadrant of left female breast',
       'Malignant neoplasm of breast female unspecified',
       'Malignant neoplasm of unspecified site of left female breast',
       'Malignant neoplasm of lower-outer quadrant of left female breast',
       'Malignant neoplasm of upper-outer quadrant of female breast',
       'Malignant neoplasm of upper-outer quadrant of left female breast',
       'Malignant neoplasm of overlapping site of left female breast',
       'Malignant neoplasm of unspecified site of right female breast',
       'Malignant neoplasm of lower-inner quadrant of left female breast',
       'Malignant neoplasm of lower-inner quadrant of right female breast',
       'Malignant neoplasm of central portion of right female breast',
       'Malignant neoplasm of central portion of female breast',
       'Malignant neoplasm of breast of unspecified site, female',
       'Malignant neoplasm of overlapping site of right female breast',
       'Malignant neoplasm of other specified site of female breast',
       'Malignant neoplasm of lower-outer quadrant of right female breast',
       'Malignant neoplasm of lower-inner quadrant of female breast',
       'Malignant neoplasm of upper-inner quadrant of right female breast',
       'Malignant neoplasm of nipple and areola right female breast',
       'Malignant neoplasm of lower-outer quadrant of breast female',
       'Malignant neoplasm of nipple and areola left female breast',
       'Malignant neoplasm of upper-outer quadrant of unspecified female breast',
       'Malignant neoplasm of upper-inner quadrant of female breast',
       'Malignant neoplasm of axillary tail of right female breast',
       'Malignant neoplasm of axillary tail of left female breast',
       'Malignant neoplasm of central portion of unspecified female breast',
       'Malignant neoplasm of overlapping site of unspecified female breast',
       'Malignant neoplasm of axillary tail of female breast',
       'Malignant neoplasm of upper-outer quadrant of breast female',
       'Malignant neoplasm of axillary tail of unspecified female breast',
       'Secondary malignant neoplasm of breast',
       'Malignant neoplasm of overlapping site of breast female',
       'Malignant neoplasm of lower-outer quadrant of female breast',
       'Malignant neoplasm of upper-inner quadrant of unspecified female breast',
       'Malignant neoplasm of lower-inner quadrant of unspecified female breast',
       'Malignant neoplasm of nipple and areola unspecified female breast',
       'Malignant neoplasm of lower-outer quadrant of unspecified female breast',
       'Malignant neoplasm of unspecified site of unspecified male breast',
       'Malignant neoplasm of nipple and areola right male breast',
       'Malignant neoplasm of upper-inner quadrant of breast female',
       'Malignant neoplasm of central portion of breast female',
       'Malignant neoplasm of lower-inner quadrant of breast female',
       'Malignant neoplasm of breast of unspecified site',
       'Malignant neoplasm of other and unspecified site of male breast',
       'Malignant neoplasm of nipple and areola female',
       'Malignant neoplasm of upper-outer quadrant of right male breast'],
      dtype=object)
In [16]:
train.breast_cancer_diagnosis_desc.value_counts() #remove extract1 , Category , breast_cancer_diagnosis_desc
Out[16]:
Malignant neoplasm of breast female unspecified                            1982
Malignant neoplasm of unspecified site of right female breast              1797
Malignant neoplasm of unspecified site of left female breast               1712
Malignant neoplasm of unspecified site of unspecified female breast        1467
Malignant neoplasm of upper-outer quadrant of right female breast           978
Malignant neoplasm of upper-outer quadrant of left female breast            877
Malignant neoplasm of overlapping site of right female breast               491
Malignant neoplasm of overlapping site of left female breast                419
Malignant neoplasm of upper-outer quadrant of female breast                 389
Malignant neoplasm of other specified site of female breast                 307
Malignant neoplasm of upper-inner quadrant of left female breast            293
Malignant neoplasm of upper-inner quadrant of right female breast           276
Malignant neoplasm of lower-outer quadrant of right female breast           213
Malignant neoplasm of central portion of left female breast                 209
Malignant neoplasm of central portion of right female breast                208
Malignant neoplasm of lower-outer quadrant of left female breast            176
Malignant neoplasm of lower-inner quadrant of left female breast            159
Malignant neoplasm of lower-inner quadrant of right female breast           138
Malignant neoplasm of nipple and areola right female breast                 108
Malignant neoplasm of nipple and areola left female breast                  105
Malignant neoplasm of upper-inner quadrant of female breast                  98
Malignant neoplasm of central portion of female breast                       88
Malignant neoplasm of lower-outer quadrant of female breast                  71
Malignant neoplasm of overlapping site of unspecified female breast          54
Malignant neoplasm of upper-outer quadrant of unspecified female breast      48
Malignant neoplasm of breast of unspecified site, female                     37
Malignant neoplasm of lower-inner quadrant of female breast                  34
Malignant neoplasm of axillary tail of left female breast                    29
Malignant neoplasm of axillary tail of right female breast                   25
Malignant neoplasm of lower-inner quadrant of unspecified female breast      16
Malignant neoplasm of nipple and areola unspecified female breast            13
Malignant neoplasm of axillary tail of female breast                         12
Malignant neoplasm of upper-inner quadrant of unspecified female breast      11
Malignant neoplasm of central portion of unspecified female breast           11
Malignant neoplasm of upper-outer quadrant of breast female                   9
Secondary malignant neoplasm of breast                                        9
Malignant neoplasm of overlapping site of breast female                       8
Malignant neoplasm of lower-outer quadrant of unspecified female breast       8
Malignant neoplasm of axillary tail of unspecified female breast              3
Malignant neoplasm of breast of unspecified site                              3
Malignant neoplasm of unspecified site of unspecified male breast             3
Malignant neoplasm of upper-inner quadrant of breast female                   3
Malignant neoplasm of central portion of breast female                        2
Malignant neoplasm of nipple and areola female                                1
Malignant neoplasm of other and unspecified site of male breast               1
Malignant neoplasm of lower-outer quadrant of breast female                   1
Malignant neoplasm of lower-inner quadrant of breast female                   1
Malignant neoplasm of nipple and areola right male breast                     1
Malignant neoplasm of upper-outer quadrant of right male breast               1
Name: breast_cancer_diagnosis_desc, dtype: int64
In [17]:
train[train['metastatic_cancer_diagnosis_code']=="C79.81"].breast_cancer_diagnosis_code.unique()
Out[17]:
array([], dtype=object)
In [18]:
# sns.countplot(data= train , x= "extract1" , hue ="DiagPeriodL90D")
In [19]:
def extract_left_right(df) : 
    df['Left'] = df['breast_cancer_diagnosis_desc'].apply(lambda x : 1 if 'left' in x else 0)
    df['Right'] = df['breast_cancer_diagnosis_desc'].apply(lambda x : 1 if 'right' in x else 0)
    return df

train = extract_left_right(train)
test = extract_left_right(test)
In [20]:
def ICD10(df):
    df['ICD10'] = df['breast_cancer_diagnosis_code'].apply(lambda x : 'C' in x).astype('int')
    return df
    
    
train = ICD10(train)
test = ICD10(test)
In [21]:
ICD9_to10 = {"1748" : "C50.81" ,
'1745' : "C50.51",
"19881" : "C79.81",
'1759' : "C50.92",
'1742' : "C50.21",
'1746' : "C50.61",
'1743' : "C50.31",
"1749" : "C50.91",
"1744" : "C50.41",
'1741' : "C50.11"}

def ICD9_10(df) : 
    df['breast_cancer_diagnosis_code'] = df['breast_cancer_diagnosis_code'].apply(lambda x: ICD9_to10[x] if x in ICD9_to10 else (x[:3] + '.' + x[3:] if len(x) > 3 else x[:3] + '.'))
    return df

train = ICD9_10(train)
test = ICD9_10(test)
In [22]:
def update_diagnosis(row):
    if row["breast_cancer_diagnosis_code"] == 'C79.81':
        row["breast_cancer_diagnosis_code"] = "C50.919"
        row["breast_cancer_diagnosis_desc"] = "Malignant neoplasm of breast"
    return row

train = train.apply(update_diagnosis, axis=1)
test = test.apply(update_diagnosis, axis=1)


def update_diagnosis2(row):
    if row["breast_cancer_diagnosis_code"] == 'C50.219':
        
        row["breast_cancer_diagnosis_desc"] = "Malignant neoplasm of upper-inner quadrant of female breast"
    return row

train = train.apply(update_diagnosis2, axis=1)
test = test.apply(update_diagnosis2, axis=1)
In [ ]:
 
In [23]:
True_ICD  = {'Malignant neoplasm of unspecified site of left male breast' : "Malignant neoplasm of breast of unspecified site of male breast",
'Malignant neoplasm of unspecified site of right male breast' : "Malignant neoplasm of breast of unspecified site of male breast",
'Malignant neoplasm of central portion of breast female' : "Malignant neoplasm of central portion of breast, female breast",
'Malignant neoplasm of lower-outer quadrant of breast female' : "Malignant neoplasm of lower-outer quadrant of female breast",
'Malignant neoplasm of nipple and areola female' : "Malignant neoplasm of nipple and areola, female breast",
'Malignant neoplasm of nipple and areola right male breast' : "Malignant neoplasm of nipple and areola, male breast",
'Malignant neoplasm of other and unspecified site of male breast' :"Malignant neoplasm of breast of unspecified site of male breast",

"Malignant neoplasm of axillary tail of female breast" : "Malignant neoplasm of axillary tail of female breast",
"Malignant neoplasm of axillary tail of left female breast" : "Malignant neoplasm of axillary tail of female breast",
'Malignant neoplasm of axillary tail of right female breast' : "Malignant neoplasm of axillary tail of female breast",
'Malignant neoplasm of breast female unspecified' : "Malignant neoplasm of breast of unspecified site of female breast",
"Malignant neoplasm of upper-outer quadrant of female breast" : "Malignant neoplasm of upper-outer quadrant of female breast" ,
"Malignant neoplasm of axillary tail of female breast" :"Malignant neoplasm of axillary tail of female breast", 
"Malignant neoplasm of breast of unspecified site, female" : "Malignant neoplasm of breast of unspecified site of female breast",
"Malignant neoplasm of upper-outer quadrant of unspecified female breast" :"Malignant neoplasm of upper-outer quadrant of female breast",
"Malignant neoplasm of overlapping site of left female breast" :"Malignant neoplasm of overlapping sites of female breast",
"Malignant neoplasm of lower-inner quadrant of female breast": "Malignant neoplasm of lower-inner quadrant of female breast",
"Malignant neoplasm of breast of unspecified site": "Malignant neoplasm of breast of unspecified site of male breast" ,
"Malignant neoplasm of upper-outer quadrant of breast female" : "Malignant neoplasm of upper-outer quadrant of female breast",
"Malignant neoplasm of upper-inner quadrant of left female breast" : "Malignant neoplasm of upper-inner quadrant of female breast",
"Malignant neoplasm of central portion of right female breast" : "Malignant neoplasm of central portion of breast, female breast",
"Malignant neoplasm of central portion of unspecified female breast" : "Malignant neoplasm of central portion of breast, female breast",
"Malignant neoplasm of upper-outer quadrant of right male breast" : "Malignant neoplasm of upper-outer quadrant of male breast",
"Malignant neoplasm of central portion of left female breast" :  "Malignant neoplasm of central portion of breast, female breast",
"Secondary malignant neoplasm of breast" : "Secondary malignant neoplasm of breast",
"Malignant neoplasm of axillary tail of left female breast" : "Malignant neoplasm of axillary tail of female breast",
"Malignant neoplasm of overlapping site of unspecified female breast" : "Malignant neoplasm of overlapping sites of female breast",
"Malignant neoplasm of unspecified site of right female breast" : "Malignant neoplasm of breast of unspecified site of female breast",
"Malignant neoplasm of breast female unspecified" : "Malignant neoplasm of breast of unspecified site of female breast" , 
"Malignant neoplasm of lower-inner quadrant of breast female" : "Malignant neoplasm of lower-inner quadrant of female breast",
"Malignant neoplasm of nipple and areola right female breast" : "Malignant neoplasm of nipple and areola, female breast",
"Malignant neoplasm of upper-inner quadrant of breast female" : "Malignant neoplasm of upper-inner quadrant of female breast",
"Malignant neoplasm of lower-outer quadrant of left female breast" : "Malignant neoplasm of lower-outer quadrant of female breast",
"Malignant neoplasm of lower-inner quadrant of right female breast" : "Malignant neoplasm of lower-inner quadrant of female breast",
"Malignant neoplasm of nipple and areola left female breast" : "Malignant neoplasm of nipple and areola, female breast",
"Malignant neoplasm of central portion of female breast" : "Malignant neoplasm of central portion of breast, female breast",
"Malignant neoplasm of unspecified site of unspecified male breast" : "Malignant neoplasm of breast of unspecified site of male breast" ,  
"Malignant neoplasm of upper-inner quadrant of right female breast" : "Malignant neoplasm of upper-inner quadrant of female breast",
"Malignant neoplasm of upper-outer quadrant of right female breast" : "Malignant neoplasm of upper-outer quadrant of female breast",
"Malignant neoplasm of axillary tail of unspecified female breast" : "Malignant neoplasm of axillary tail of female breast",
"Malignant neoplasm of lower-outer quadrant of right female breas" : "Malignant neoplasm of lower-outer quadrant of female breast",
"Malignant neoplasm of upper-inner quadrant of female breast" : "Malignant neoplasm of upper-inner quadrant of female breast",
"Malignant neoplasm of unspecified site of unspecified female breast" : "Malignant neoplasm of breast of unspecified site of female breast",
"Malignant neoplasm of other specified site of female breast" : "Malignant neoplasm of overlapping sites of female breast",
"Malignant neoplasm of axillary tail of right female breast" : "Malignant neoplasm of axillary tail of female breast",
"Malignant neoplasm of lower-outer quadrant of female breast" : "Malignant neoplasm of lower-outer quadrant of female breast",
"Malignant neoplasm of nipple and areola unspecified female breast" : "Malignant neoplasm of nipple and areola, female breast",
"Malignant neoplasm of lower-outer quadrant of unspecified female breast" : "Malignant neoplasm of lower-outer quadrant of female breast",
"Malignant neoplasm of overlapping site of right female breast" : "Malignant neoplasm of overlapping sites of female breast",
"Malignant neoplasm of lower-inner quadrant of left female breast" : "Malignant neoplasm of lower-inner quadrant of female breast",
"Malignant neoplasm of upper-outer quadrant of left female breast" : "Malignant neoplasm of upper-outer quadrant of female breast",
"Malignant neoplasm of overlapping site of breast female" : "Malignant neoplasm of overlapping sites of female breast",
"Malignant neoplasm of lower-inner quadrant of unspecified female breast" : "Malignant neoplasm of lower-inner quadrant of female breast",
"Malignant neoplasm of upper-inner quadrant of unspecified female breast" : "Malignant neoplasm of upper-outer quadrant of female breast" ,
"Malignant neoplasm of lower-outer quadrant of right female breast" : "Malignant neoplasm of lower-outer quadrant of female breast" , 
'Malignant neoplasm of unspecified site of left female breast': "Malignant neoplasm of breast of unspecified site of female breast" ,

'Malignant neoplasm of unspecified site of left female breast' :  "Malignant neoplasm of breast of unspecified site of female breast" ,
"Malignant neoplasm of breast" : "Malignant neoplasm of breast"} 

def correct_desc(df) : 
    df['breast_cancer_diagnosis_desc'] = df['breast_cancer_diagnosis_desc'].map(True_ICD)
    return df

train = correct_desc(train)
test = correct_desc(test)
In [ ]:
 
In [24]:
train[train['breast_cancer_diagnosis_code'] == 'C50.9']['breast_cancer_diagnosis_desc'].unique()
correct_code = {'C50.9' : 'C50.92'  }
train['breast_cancer_diagnosis_code'] = train['breast_cancer_diagnosis_code'].apply(lambda x: correct_code[x] if x in correct_code else x)
test['breast_cancer_diagnosis_code'] = test['breast_cancer_diagnosis_code'].apply(lambda x: correct_code[x] if x in correct_code else x)
In [25]:
train.breast_cancer_diagnosis_code.unique()
Out[25]:
array(['C50.919', 'C50.411', 'C50.112', 'C50.212', 'C50.91', 'C50.912',
       'C50.512', 'C50.41', 'C50.412', 'C50.812', 'C50.911', 'C50.312',
       'C50.311', 'C50.111', 'C50.11', 'C50.811', 'C50.81', 'C50.511',
       'C50.31', 'C50.211', 'C50.011', 'C50.51', 'C50.012', 'C50.419',
       'C50.21', 'C50.611', 'C50.612', 'C50.119', 'C50.819', 'C50.61',
       'C50.619', 'C50.219', 'C50.319', 'C50.019', 'C50.519', 'C50.929',
       'C50.021', 'C50.92', 'C50.01', 'C50.421'], dtype=object)
In [26]:
def male_female(df) : 
    df["male_patient"] = df['breast_cancer_diagnosis_code'].apply(lambda x : 1 if x[4] == '2' else 0)
    return df


train = male_female(train)
test = male_female(test)
In [27]:
# add unspecified to missing direction
def add_unspecified(df) : 
    df['breast_cancer_diagnosis_code'] = df['breast_cancer_diagnosis_code'].apply(lambda x : x+'9' if len(x)==6 else x)
    return df

train = add_unspecified(train)
test = add_unspecified(test)
In [28]:
extract_place = {'Malignant neoplasm of breast of unspecified site of female breast' : "breast of unspecified site"  ,
                 "Malignant neoplasm of upper-outer quadrant of female breast":"upper-outer quadrant" , 
                  "Malignant neoplasm of central portion of breast, female breast":"central portion" , 
                 'Malignant neoplasm of upper-inner quadrant of female breast':"upper-inner quadrant" , 
                 'Malignant neoplasm of lower-outer quadrant of female breast' : "lower-outer quadrant" , 
                 'Malignant neoplasm of overlapping sites of female breast' : "overlapping sites" , 
                 'Malignant neoplasm of lower-inner quadrant of female breast':"lower-inner quadrant" ,
                
                 'Malignant neoplasm of nipple and areola, female breast' : "nipple and areola" ,
                 'Malignant neoplasm of axillary tail of female breast' : "axillary tail" , 
                 
                 'Malignant neoplasm of breast of unspecified site of male breast' : "breast of unspecified site" , 
                 'Malignant neoplasm of nipple and areola, male breast': "nipple and areola" , 
                 'Malignant neoplasm of upper-outer quadrant of male breast' : "upper-outer quadrant"}


def extract_cancer_place(df) : 
    df['Place'] = df['breast_cancer_diagnosis_desc'].map(extract_place)
    return df

train = extract_cancer_place(train)
test = extract_cancer_place(test)
In [29]:
train_patient_race = train.patient_race
test_patient_race = test.patient_race
In [30]:
train.drop('patient_gender' , axis=1 , inplace =True)
test.drop('patient_gender' , axis=1 , inplace =True)

train.drop('patient_race' , axis=1 , inplace =True)
test.drop('patient_race' , axis=1 , inplace =True)
train.drop(['metastatic_first_novel_treatment_type',"metastatic_first_novel_treatment"] ,axis = 1 , inplace =True)
test.drop(['metastatic_first_novel_treatment_type',"metastatic_first_novel_treatment" ] ,axis = 1 , inplace =True)
In [31]:
train.head()
Out[31]:
patient_id payer_type patient_state patient_zip3 patient_age bmi breast_cancer_diagnosis_code breast_cancer_diagnosis_desc metastatic_cancer_diagnosis_code Region Division population density age_median age_under_10 age_10_to_19 age_20s age_30s age_40s age_50s age_60s age_70s age_over_80 married divorced never_married widowed family_size family_dual_income income_household_median income_household_under_5 income_household_5_to_10 income_household_10_to_15 income_household_15_to_20 income_household_20_to_25 income_household_25_to_35 income_household_35_to_50 income_household_50_to_75 income_household_75_to_100 income_household_100_to_150 income_household_150_over income_household_six_figure income_individual_median home_ownership housing_units home_value rent_median rent_burden education_less_highschool education_highschool education_some_college education_bachelors education_graduate education_college_or_above education_stem_degree labor_force_participation unemployment_rate self_employed farmer race_white race_black race_asian race_native race_pacific race_other race_multiple hispanic disabled poverty limited_english commute_time health_uninsured veteran Ozone PM25 N02 DiagPeriodL90D male_1 female_1 Left Right ICD10 male_patient Place
0 475714 MEDICAID CA 924 84 NaN C50.919 Malignant neoplasm of breast of unspecified si... C7989 West Pacific 31437.75 1189.56 30.64 16.01 15.54 17.61 14.01 11.61 11.56 7.57 4.00 2.10 36.57 11.89 47.11 4.44 3.93 52.23 52996.29 3.14 4.00 6.16 5.14 6.27 10.14 13.30 20.00 12.74 11.57 7.53 19.10 24563.57 44.59 8674.50 264634.29 1165.00 37.44 33.26 29.20 25.91 8.36 3.26 11.61 39.56 61.53 8.47 13.43 0.00 44.10 13.10 5.10 1.49 0.34 27.11 8.76 66.69 12.87 22.54 10.10 27.81 11.20 3.50 52.24 8.65 18.61 1 49.86 50.14 0 0 1 0 breast of unspecified site
1 349367 COMMERCIAL CA 928 62 28.49 C50.411 Malignant neoplasm of upper-outer quadrant of ... C773 West Pacific 39121.88 2295.94 38.20 11.88 13.35 14.23 13.42 13.33 14.06 10.25 5.95 3.50 50.25 9.83 35.29 4.65 3.62 61.74 102741.64 2.33 1.54 2.65 2.18 2.41 5.16 7.97 13.94 12.47 19.76 29.60 49.36 41287.27 61.46 11725.67 677688.52 2003.12 34.75 14.23 19.99 29.80 23.74 12.25 35.98 47.92 65.23 5.10 15.22 0.03 54.03 2.53 20.83 0.59 0.30 11.65 10.08 37.95 8.96 10.11 8.06 30.61 7.02 4.10 42.30 8.49 20.11 1 49.89 50.11 0 1 1 0 upper-outer quadrant
2 138632 COMMERCIAL TX 760 43 38.09 C50.112 Malignant neoplasm of central portion of breas... C773 South West South Central 21996.68 626.24 37.91 13.03 14.46 12.53 13.54 12.86 12.77 11.43 6.57 2.81 55.75 12.33 27.20 4.71 3.26 55.80 85984.74 2.48 1.30 2.72 2.94 2.77 6.76 12.06 15.84 13.56 20.88 18.68 39.55 40399.03 72.75 7786.58 237713.05 1235.91 29.36 10.81 27.04 32.37 19.68 10.12 29.79 37.31 66.43 4.56 13.72 3.65 75.82 9.23 3.62 0.46 0.15 3.82 6.90 19.37 11.25 9.66 3.36 31.39 15.07 7.45 40.11 7.64 14.84 1 50.12 49.88 1 0 1 0 central portion
3 617843 COMMERCIAL CA 926 45 NaN C50.212 Malignant neoplasm of upper-inner quadrant of ... C773 West Pacific 32795.33 1896.22 42.87 10.07 12.14 12.54 12.46 12.65 14.85 12.28 8.22 4.76 52.60 11.62 31.14 4.62 3.10 54.56 120533.83 3.44 1.27 2.18 2.21 2.10 4.38 5.89 10.90 10.72 18.85 38.06 56.91 55336.29 59.22 12171.30 1012474.22 2354.74 32.03 5.84 12.15 26.27 33.29 22.46 55.75 48.94 64.43 5.26 18.50 0.05 65.01 1.44 18.85 0.43 0.25 5.43 8.61 16.72 8.85 8.69 5.28 27.56 4.40 4.81 42.07 7.23 15.89 0 49.07 50.93 1 0 1 1 upper-inner quadrant
4 817482 COMMERCIAL ID 836 55 NaN C50.919 Malignant neoplasm of breast of unspecified si... C773 West Mountain 10886.26 116.89 43.47 10.82 13.98 9.49 10.36 12.60 14.99 14.84 9.46 3.47 57.88 14.96 21.76 5.41 3.35 47.21 61075.13 2.59 1.96 3.17 3.24 4.78 11.46 15.66 22.43 12.48 13.62 8.61 22.23 29073.18 77.10 3768.06 249845.72 919.74 27.03 11.58 29.59 39.17 13.98 5.68 19.66 42.33 57.49 4.26 13.03 6.89 86.71 0.43 0.66 0.76 0.11 5.08 6.26 13.33 15.28 11.22 1.95 26.17 12.09 13.11 41.36 4.11 11.72 0 52.31 47.69 0 0 0 0 breast of unspecified site
In [ ]:
 
In [ ]:
 
In [32]:
AllData = pd.DataFrame()
for col in test.columns : 
    L1 = list(train[col].values)
    L2 = list(test[col].values)
    L = L1 +L2
    AllData[col] = L
    
    
for col in AllData.breast_cancer_diagnosis_desc.unique() :
    print(50*'#')
    print(col)
    print(AllData[AllData['breast_cancer_diagnosis_desc'] == col].breast_cancer_diagnosis_code.unique())
##################################################
Malignant neoplasm of breast of unspecified site of female breast
['C50.919' 'C50.912' 'C50.911']
##################################################
Malignant neoplasm of upper-outer quadrant of female breast
['C50.411' 'C50.419' 'C50.412']
##################################################
Malignant neoplasm of central portion of breast, female breast
['C50.112' 'C50.111' 'C50.119']
##################################################
Malignant neoplasm of upper-inner quadrant of female breast
['C50.212' 'C50.211' 'C50.219']
##################################################
Malignant neoplasm of lower-outer quadrant of female breast
['C50.512' 'C50.511' 'C50.519']
##################################################
Malignant neoplasm of overlapping sites of female breast
['C50.812' 'C50.811' 'C50.819']
##################################################
Malignant neoplasm of lower-inner quadrant of female breast
['C50.312' 'C50.311' 'C50.319']
##################################################
Malignant neoplasm of nipple and areola, female breast
['C50.011' 'C50.012' 'C50.019']
##################################################
Malignant neoplasm of axillary tail of female breast
['C50.611' 'C50.612' 'C50.619']
##################################################
Malignant neoplasm of breast
['C50.919']
##################################################
Malignant neoplasm of breast of unspecified site of male breast
['C50.929' 'C50.922' 'C50.921']
##################################################
Malignant neoplasm of nipple and areola, male breast
['C50.021']
##################################################
Malignant neoplasm of upper-outer quadrant of male breast
['C50.421']
In [33]:
for col in test.breast_cancer_diagnosis_desc.unique() :
    print(50*'#')
    print(col)
    print(test[test['breast_cancer_diagnosis_desc'] == col].breast_cancer_diagnosis_code.unique())
##################################################
Malignant neoplasm of upper-outer quadrant of female breast
['C50.412' 'C50.411' 'C50.419']
##################################################
Malignant neoplasm of breast of unspecified site of female breast
['C50.912' 'C50.911' 'C50.919']
##################################################
Malignant neoplasm of overlapping sites of female breast
['C50.819' 'C50.811' 'C50.812']
##################################################
Malignant neoplasm of upper-inner quadrant of female breast
['C50.212' 'C50.211' 'C50.219']
##################################################
Malignant neoplasm of central portion of breast, female breast
['C50.112' 'C50.111' 'C50.119']
##################################################
Malignant neoplasm of lower-outer quadrant of female breast
['C50.511' 'C50.512' 'C50.519']
##################################################
Malignant neoplasm of axillary tail of female breast
['C50.612' 'C50.619' 'C50.611']
##################################################
Malignant neoplasm of nipple and areola, female breast
['C50.012' 'C50.011' 'C50.019']
##################################################
Malignant neoplasm of lower-inner quadrant of female breast
['C50.311' 'C50.312' 'C50.319']
##################################################
Malignant neoplasm of breast of unspecified site of male breast
['C50.929' 'C50.922' 'C50.921']
##################################################
Malignant neoplasm of breast
['C50.919']
##################################################
Malignant neoplasm of upper-outer quadrant of male breast
['C50.421']
In [34]:
for col in train.breast_cancer_diagnosis_desc.unique() :
    print(50*'#')
    print(col)
    print(train[train['breast_cancer_diagnosis_desc'] == col].breast_cancer_diagnosis_code.unique())
##################################################
Malignant neoplasm of breast of unspecified site of female breast
['C50.919' 'C50.912' 'C50.911']
##################################################
Malignant neoplasm of upper-outer quadrant of female breast
['C50.411' 'C50.419' 'C50.412']
##################################################
Malignant neoplasm of central portion of breast, female breast
['C50.112' 'C50.111' 'C50.119']
##################################################
Malignant neoplasm of upper-inner quadrant of female breast
['C50.212' 'C50.211' 'C50.219']
##################################################
Malignant neoplasm of lower-outer quadrant of female breast
['C50.512' 'C50.511' 'C50.519']
##################################################
Malignant neoplasm of overlapping sites of female breast
['C50.812' 'C50.811' 'C50.819']
##################################################
Malignant neoplasm of lower-inner quadrant of female breast
['C50.312' 'C50.311' 'C50.319']
##################################################
Malignant neoplasm of nipple and areola, female breast
['C50.011' 'C50.012' 'C50.019']
##################################################
Malignant neoplasm of axillary tail of female breast
['C50.611' 'C50.612' 'C50.619']
##################################################
Malignant neoplasm of breast
['C50.919']
##################################################
Malignant neoplasm of breast of unspecified site of male breast
['C50.929']
##################################################
Malignant neoplasm of nipple and areola, male breast
['C50.021']
##################################################
Malignant neoplasm of upper-outer quadrant of male breast
['C50.421']
In [35]:
patient_zip3 = set(train['patient_zip3'])


stocker  = dict()
for zp in patient_zip3 : 
    stocker[zp] = train[train['patient_zip3'] == zp].patient_state.value_counts().sort_values().index[-1]
    print("#"*50)
    print(zp , train[train['patient_zip3'] == zp].patient_state.value_counts().sort_values())
    
for i in train.index:
    train.at[i, "patient_state"] = stocker.get(train.at[i, "patient_zip3"], None)
##################################################
101 NY    2
Name: patient_state, dtype: int64
##################################################
103 FL     1
NJ     2
NY    32
Name: patient_state, dtype: int64
##################################################
104 FL      1
NC      1
PA      2
NJ      2
NY    106
Name: patient_state, dtype: int64
##################################################
105 NJ     1
NY    32
Name: patient_state, dtype: int64
##################################################
106 NY    5
Name: patient_state, dtype: int64
##################################################
107 NY    11
Name: patient_state, dtype: int64
##################################################
108 NY    7
Name: patient_state, dtype: int64
##################################################
109 GA     1
NY    16
Name: patient_state, dtype: int64
##################################################
110 NY    15
Name: patient_state, dtype: int64
##################################################
111 NJ     1
NY    12
Name: patient_state, dtype: int64
##################################################
112 RI      1
PA      1
CT      1
CA      1
TX      1
NJ      7
NY    180
Name: patient_state, dtype: int64
##################################################
113 FL     1
WA     1
NJ     1
VA     1
NY    67
Name: patient_state, dtype: int64
##################################################
114 NJ     2
FL     2
NY    53
Name: patient_state, dtype: int64
##################################################
115 PA     1
NY    39
Name: patient_state, dtype: int64
##################################################
116 NY    8
Name: patient_state, dtype: int64
##################################################
117 NC     1
FL     3
NY    67
Name: patient_state, dtype: int64
##################################################
118 NY    1
AZ    1
Name: patient_state, dtype: int64
##################################################
119 FL     1
NY    13
Name: patient_state, dtype: int64
##################################################
120 NY    27
Name: patient_state, dtype: int64
##################################################
121 NY    25
Name: patient_state, dtype: int64
##################################################
122 CA     1
NY    13
Name: patient_state, dtype: int64
##################################################
123 NY    14
Name: patient_state, dtype: int64
##################################################
124 NY    11
Name: patient_state, dtype: int64
##################################################
125 NY    23
Name: patient_state, dtype: int64
##################################################
126 NY    3
Name: patient_state, dtype: int64
##################################################
127 SC    1
NY    7
Name: patient_state, dtype: int64
##################################################
128 NY    19
Name: patient_state, dtype: int64
##################################################
129 NY    4
Name: patient_state, dtype: int64
##################################################
130 NY    5
Name: patient_state, dtype: int64
##################################################
131 NY    2
Name: patient_state, dtype: int64
##################################################
132 NY    6
Name: patient_state, dtype: int64
##################################################
133 NY    3
Name: patient_state, dtype: int64
##################################################
134 NY    7
Name: patient_state, dtype: int64
##################################################
135 NY    2
Name: patient_state, dtype: int64
##################################################
136 NY    9
Name: patient_state, dtype: int64
##################################################
137 NY    4
Name: patient_state, dtype: int64
##################################################
138 NY    7
Name: patient_state, dtype: int64
##################################################
139 NY    1
Name: patient_state, dtype: int64
##################################################
140 NY    39
Name: patient_state, dtype: int64
##################################################
141 NY    25
Name: patient_state, dtype: int64
##################################################
142 NY    50
Name: patient_state, dtype: int64
##################################################
143 NY    6
Name: patient_state, dtype: int64
##################################################
144 NY    9
Name: patient_state, dtype: int64
##################################################
145 NY    11
Name: patient_state, dtype: int64
##################################################
146 NY    23
Name: patient_state, dtype: int64
##################################################
147 NY    8
Name: patient_state, dtype: int64
##################################################
148 NY    5
Name: patient_state, dtype: int64
##################################################
149 NY    1
Name: patient_state, dtype: int64
##################################################
150 PA    6
Name: patient_state, dtype: int64
##################################################
151 PA    11
Name: patient_state, dtype: int64
##################################################
152 PA    11
Name: patient_state, dtype: int64
##################################################
154 PA    2
Name: patient_state, dtype: int64
##################################################
155 PA    1
Name: patient_state, dtype: int64
##################################################
156 PA    9
Name: patient_state, dtype: int64
##################################################
157 PA    1
Name: patient_state, dtype: int64
##################################################
158 PA    2
Name: patient_state, dtype: int64
##################################################
159 PA    2
Name: patient_state, dtype: int64
##################################################
160 PA    5
Name: patient_state, dtype: int64
##################################################
161 PA    2
Name: patient_state, dtype: int64
##################################################
162 PA    1
Name: patient_state, dtype: int64
##################################################
163 PA    1
Name: patient_state, dtype: int64
##################################################
164 PA    4
Name: patient_state, dtype: int64
##################################################
165 PA    7
Name: patient_state, dtype: int64
##################################################
166 PA    3
Name: patient_state, dtype: int64
##################################################
168 PA    2
Name: patient_state, dtype: int64
##################################################
169 PA    2
Name: patient_state, dtype: int64
##################################################
170 MN     1
PA    20
Name: patient_state, dtype: int64
##################################################
171 OK    1
PA    6
Name: patient_state, dtype: int64
##################################################
172 PA    4
Name: patient_state, dtype: int64
##################################################
173 PA    10
Name: patient_state, dtype: int64
##################################################
174 PA    4
Name: patient_state, dtype: int64
##################################################
175 PA    9
Name: patient_state, dtype: int64
##################################################
176 PA    6
Name: patient_state, dtype: int64
##################################################
177 PA    7
Name: patient_state, dtype: int64
##################################################
178 PA    13
Name: patient_state, dtype: int64
##################################################
179 PA    6
Name: patient_state, dtype: int64
##################################################
180 PA    24
Name: patient_state, dtype: int64
##################################################
181 PR    1
PA    9
Name: patient_state, dtype: int64
##################################################
182 PA    5
Name: patient_state, dtype: int64
##################################################
183 NY     1
PA    14
Name: patient_state, dtype: int64
##################################################
184 PA    6
Name: patient_state, dtype: int64
##################################################
185 PA    5
Name: patient_state, dtype: int64
##################################################
186 PA    11
Name: patient_state, dtype: int64
##################################################
187 PA    3
Name: patient_state, dtype: int64
##################################################
189 PA    32
Name: patient_state, dtype: int64
##################################################
190 DE     1
KY     1
PA    62
Name: patient_state, dtype: int64
##################################################
191 AR     1
LA     1
DE     1
PA    88
Name: patient_state, dtype: int64
##################################################
193 NJ     1
CA     1
PA    16
Name: patient_state, dtype: int64
##################################################
194 PA    37
Name: patient_state, dtype: int64
##################################################
195 PA    3
Name: patient_state, dtype: int64
##################################################
196 FL    1
PA    5
Name: patient_state, dtype: int64
##################################################
197 DE    7
Name: patient_state, dtype: int64
##################################################
198 DE    6
Name: patient_state, dtype: int64
##################################################
199 DE    16
Name: patient_state, dtype: int64
##################################################
200 DC    20
Name: patient_state, dtype: int64
##################################################
201 VA    23
Name: patient_state, dtype: int64
##################################################
206 MD    4
Name: patient_state, dtype: int64
##################################################
207 MD    11
Name: patient_state, dtype: int64
##################################################
208 MA     1
MD    11
Name: patient_state, dtype: int64
##################################################
209 TX    1
MD    3
Name: patient_state, dtype: int64
##################################################
210 MD    7
Name: patient_state, dtype: int64
##################################################
211 MD    8
Name: patient_state, dtype: int64
##################################################
212 VA     1
MD    13
Name: patient_state, dtype: int64
##################################################
215 MD    3
Name: patient_state, dtype: int64
##################################################
216 MD    2
Name: patient_state, dtype: int64
##################################################
217 MD    8
Name: patient_state, dtype: int64
##################################################
220 VA    11
Name: patient_state, dtype: int64
##################################################
221 VA    15
Name: patient_state, dtype: int64
##################################################
222 VA    5
Name: patient_state, dtype: int64
##################################################
223 VA    6
Name: patient_state, dtype: int64
##################################################
224 VA    8
Name: patient_state, dtype: int64
##################################################
225 VA    6
Name: patient_state, dtype: int64
##################################################
226 VA    7
Name: patient_state, dtype: int64
##################################################
227 VA    6
Name: patient_state, dtype: int64
##################################################
228 VA    10
Name: patient_state, dtype: int64
##################################################
229 VA    16
Name: patient_state, dtype: int64
##################################################
230 VA    16
Name: patient_state, dtype: int64
##################################################
231 VA    17
Name: patient_state, dtype: int64
##################################################
232 NC     1
VA    27
Name: patient_state, dtype: int64
##################################################
233 CO     1
VA    19
Name: patient_state, dtype: int64
##################################################
234 VA    30
Name: patient_state, dtype: int64
##################################################
235 OH     1
NY     1
VA    12
Name: patient_state, dtype: int64
##################################################
236 VA    21
Name: patient_state, dtype: int64
##################################################
237 VA    3
Name: patient_state, dtype: int64
##################################################
238 GA     1
VA    24
Name: patient_state, dtype: int64
##################################################
239 VA    9
Name: patient_state, dtype: int64
##################################################
240 VA    17
Name: patient_state, dtype: int64
##################################################
241 VA    11
Name: patient_state, dtype: int64
##################################################
242 VA    7
Name: patient_state, dtype: int64
##################################################
243 VA    6
Name: patient_state, dtype: int64
##################################################
244 VA    7
Name: patient_state, dtype: int64
##################################################
245 VA    18
Name: patient_state, dtype: int64
##################################################
246 VA    5
Name: patient_state, dtype: int64
##################################################
247 WV    1
Name: patient_state, dtype: int64
##################################################
248 WV    3
Name: patient_state, dtype: int64
##################################################
251 WV    1
Name: patient_state, dtype: int64
##################################################
252 WV    1
Name: patient_state, dtype: int64
##################################################
253 WV    2
Name: patient_state, dtype: int64
##################################################
254 WV    2
Name: patient_state, dtype: int64
##################################################
255 WV    1
Name: patient_state, dtype: int64
##################################################
256 WV    1
Name: patient_state, dtype: int64
##################################################
259 WV    2
Name: patient_state, dtype: int64
##################################################
260 WV    3
Name: patient_state, dtype: int64
##################################################
261 WV    1
Name: patient_state, dtype: int64
##################################################
262 WV    3
Name: patient_state, dtype: int64
##################################################
263 WV    1
Name: patient_state, dtype: int64
##################################################
264 WV    1
Name: patient_state, dtype: int64
##################################################
265 WV    1
Name: patient_state, dtype: int64
##################################################
267 WV    3
Name: patient_state, dtype: int64
##################################################
270 NC    7
Name: patient_state, dtype: int64
##################################################
271 NC    9
Name: patient_state, dtype: int64
##################################################
272 NC    12
Name: patient_state, dtype: int64
##################################################
273 NC    4
Name: patient_state, dtype: int64
##################################################
274 NC    5
Name: patient_state, dtype: int64
##################################################
275 NJ     1
NC    22
Name: patient_state, dtype: int64
##################################################
276 NC    9
Name: patient_state, dtype: int64
##################################################
277 NC    4
Name: patient_state, dtype: int64
##################################################
278 NC    11
Name: patient_state, dtype: int64
##################################################
279 NC    5
Name: patient_state, dtype: int64
##################################################
280 NC    16
Name: patient_state, dtype: int64
##################################################
281 NC    7
Name: patient_state, dtype: int64
##################################################
282 NC    20
Name: patient_state, dtype: int64
##################################################
283 NC    14
Name: patient_state, dtype: int64
##################################################
284 NC    9
Name: patient_state, dtype: int64
##################################################
285 NC    6
Name: patient_state, dtype: int64
##################################################
286 NC    8
Name: patient_state, dtype: int64
##################################################
287 NC    11
Name: patient_state, dtype: int64
##################################################
288 NC    2
Name: patient_state, dtype: int64
##################################################
290 SC    12
Name: patient_state, dtype: int64
##################################################
291 SC    10
Name: patient_state, dtype: int64
##################################################
292 SC    8
Name: patient_state, dtype: int64
##################################################
293 SC    7
Name: patient_state, dtype: int64
##################################################
294 DE     1
SC    13
Name: patient_state, dtype: int64
##################################################
295 NC     1
SC    10
Name: patient_state, dtype: int64
##################################################
296 SC    21
Name: patient_state, dtype: int64
##################################################
297 SC    13
Name: patient_state, dtype: int64
##################################################
298 SC    7
Name: patient_state, dtype: int64
##################################################
299 SC    6
Name: patient_state, dtype: int64
##################################################
300 TX      1
GA    119
Name: patient_state, dtype: int64
##################################################
301 GA    59
Name: patient_state, dtype: int64
##################################################
302 SC     1
GA    52
Name: patient_state, dtype: int64
##################################################
303 GA    48
Name: patient_state, dtype: int64
##################################################
304 GA    13
Name: patient_state, dtype: int64
##################################################
305 GA    33
Name: patient_state, dtype: int64
##################################################
306 GA    25
Name: patient_state, dtype: int64
##################################################
307 TX     1
GA    14
Name: patient_state, dtype: int64
##################################################
308 GA    7
Name: patient_state, dtype: int64
##################################################
309 GA    13
Name: patient_state, dtype: int64
##################################################
310 GA    28
Name: patient_state, dtype: int64
##################################################
312 GA    6
Name: patient_state, dtype: int64
##################################################
313 MD    1
TX    1
GA    8
Name: patient_state, dtype: int64
##################################################
314 GA    22
Name: patient_state, dtype: int64
##################################################
315 GA    27
Name: patient_state, dtype: int64
##################################################
316 GA    14
Name: patient_state, dtype: int64
##################################################
317 GA    35
Name: patient_state, dtype: int64
##################################################
318 MS    1
GA    4
Name: patient_state, dtype: int64
##################################################
319 GA    9
Name: patient_state, dtype: int64
##################################################
320 PA     1
FL    11
Name: patient_state, dtype: int64
##################################################
321 MT     1
NC     1
FL    13
Name: patient_state, dtype: int64
##################################################
322 FL    28
Name: patient_state, dtype: int64
##################################################
323 FL    7
Name: patient_state, dtype: int64
##################################################
324 FL    11
Name: patient_state, dtype: int64
##################################################
325 FL    9
Name: patient_state, dtype: int64
##################################################
326 KY    1
FL    2
Name: patient_state, dtype: int64
##################################################
327 OH     1
IL     1
FL    17
Name: patient_state, dtype: int64
##################################################
328 FL    30
Name: patient_state, dtype: int64
##################################################
329 FL    15
Name: patient_state, dtype: int64
##################################################
330 FL    66
Name: patient_state, dtype: int64
##################################################
331 FL    91
Name: patient_state, dtype: int64
##################################################
332 FL    1
Name: patient_state, dtype: int64
##################################################
333 FL    20
Name: patient_state, dtype: int64
##################################################
334 NY     1
FL    33
Name: patient_state, dtype: int64
##################################################
335 FL    22
Name: patient_state, dtype: int64
##################################################
336 FL    34
Name: patient_state, dtype: int64
##################################################
337 FL    30
Name: patient_state, dtype: int64
##################################################
338 FL    26
Name: patient_state, dtype: int64
##################################################
339 FL    23
Name: patient_state, dtype: int64
##################################################
341 FL    5
Name: patient_state, dtype: int64
##################################################
342 FL    33
Name: patient_state, dtype: int64
##################################################
344 FL    6
Name: patient_state, dtype: int64
##################################################
346 FL    26
Name: patient_state, dtype: int64
##################################################
347 OH     1
NY     1
FL    17
Name: patient_state, dtype: int64
##################################################
349 GA     1
FL    14
Name: patient_state, dtype: int64
##################################################
350 AL    5
Name: patient_state, dtype: int64
##################################################
351 AL    1
Name: patient_state, dtype: int64
##################################################
352 AL    4
Name: patient_state, dtype: int64
##################################################
354 AL    2
Name: patient_state, dtype: int64
##################################################
356 AL    7
Name: patient_state, dtype: int64
##################################################
357 AL    5
Name: patient_state, dtype: int64
##################################################
358 AL    3
Name: patient_state, dtype: int64
##################################################
359 FL    1
AL    3
Name: patient_state, dtype: int64
##################################################
360 AL    2
Name: patient_state, dtype: int64
##################################################
361 AL    1
Name: patient_state, dtype: int64
##################################################
363 AL    2
Name: patient_state, dtype: int64
##################################################
365 FL    1
AL    5
Name: patient_state, dtype: int64
##################################################
366 AL    2
Name: patient_state, dtype: int64
##################################################
367 AL    1
Name: patient_state, dtype: int64
##################################################
368 AL    7
Name: patient_state, dtype: int64
##################################################
370 IL     1
TN    15
Name: patient_state, dtype: int64
##################################################
371 GA     1
TN    13
Name: patient_state, dtype: int64
##################################################
372 TN    3
Name: patient_state, dtype: int64
##################################################
373 TN    4
Name: patient_state, dtype: int64
##################################################
374 TN    3
Name: patient_state, dtype: int64
##################################################
376 TN    4
Name: patient_state, dtype: int64
##################################################
377 TN    7
Name: patient_state, dtype: int64
##################################################
378 TN    10
Name: patient_state, dtype: int64
##################################################
379 TN    4
Name: patient_state, dtype: int64
##################################################
380 TN    7
Name: patient_state, dtype: int64
##################################################
381 TN    21
Name: patient_state, dtype: int64
##################################################
382 TN    3
Name: patient_state, dtype: int64
##################################################
383 TN    6
Name: patient_state, dtype: int64
##################################################
384 TN    6
Name: patient_state, dtype: int64
##################################################
385 TN    5
Name: patient_state, dtype: int64
##################################################
386 MS    9
Name: patient_state, dtype: int64
##################################################
387 MS    4
Name: patient_state, dtype: int64
##################################################
388 MS    3
Name: patient_state, dtype: int64
##################################################
389 MS    3
Name: patient_state, dtype: int64
##################################################
390 MS    11
Name: patient_state, dtype: int64
##################################################
391 MS    12
Name: patient_state, dtype: int64
##################################################
392 MS    12
Name: patient_state, dtype: int64
##################################################
393 MS    2
Name: patient_state, dtype: int64
##################################################
394 MS    6
Name: patient_state, dtype: int64
##################################################
395 MS    8
Name: patient_state, dtype: int64
##################################################
396 MS    3
Name: patient_state, dtype: int64
##################################################
397 MS    1
Name: patient_state, dtype: int64
##################################################
398 GA    8
Name: patient_state, dtype: int64
##################################################
400 KY    20
Name: patient_state, dtype: int64
##################################################
401 KY    8
Name: patient_state, dtype: int64
##################################################
402 SC     1
MI     1
KY    43
Name: patient_state, dtype: int64
##################################################
403 KY    14
Name: patient_state, dtype: int64
##################################################
404 KY    15
Name: patient_state, dtype: int64
##################################################
405 KY    30
Name: patient_state, dtype: int64
##################################################
406 KY    3
Name: patient_state, dtype: int64
##################################################
407 KY    7
Name: patient_state, dtype: int64
##################################################
408 KY    2
Name: patient_state, dtype: int64
##################################################
409 KY    4
Name: patient_state, dtype: int64
##################################################
410 KY    23
Name: patient_state, dtype: int64
##################################################
411 KY    8
Name: patient_state, dtype: int64
##################################################
412 KY    2
Name: patient_state, dtype: int64
##################################################
413 KY    2
Name: patient_state, dtype: int64
##################################################
414 KY    2
Name: patient_state, dtype: int64
##################################################
415 KY    3
Name: patient_state, dtype: int64
##################################################
416 KY    1
Name: patient_state, dtype: int64
##################################################
417 KY    3
Name: patient_state, dtype: int64
##################################################
418 KY    3
Name: patient_state, dtype: int64
##################################################
420 KY    6
Name: patient_state, dtype: int64
##################################################
421 KY    13
Name: patient_state, dtype: int64
##################################################
422 KY    6
Name: patient_state, dtype: int64
##################################################
423 KY    13
Name: patient_state, dtype: int64
##################################################
424 KY    4
Name: patient_state, dtype: int64
##################################################
425 KY    3
Name: patient_state, dtype: int64
##################################################
426 KY    5
Name: patient_state, dtype: int64
##################################################
427 KY    11
Name: patient_state, dtype: int64
##################################################
430 OH    60
Name: patient_state, dtype: int64
##################################################
431 OH    26
Name: patient_state, dtype: int64
##################################################
432 OH    52
Name: patient_state, dtype: int64
##################################################
433 OH    9
Name: patient_state, dtype: int64
##################################################
434 OH    12
Name: patient_state, dtype: int64
##################################################
435 CO     1
OH    17
Name: patient_state, dtype: int64
##################################################
436 OH    22
Name: patient_state, dtype: int64
##################################################
437 OH    13
Name: patient_state, dtype: int64
##################################################
438 OH    4
Name: patient_state, dtype: int64
##################################################
439 OH    7
Name: patient_state, dtype: int64
##################################################
440 OH    72
Name: patient_state, dtype: int64
##################################################
441 OH    74
Name: patient_state, dtype: int64
##################################################
442 TX     1
OH    43
Name: patient_state, dtype: int64
##################################################
443 OH    26
Name: patient_state, dtype: int64
##################################################
444 OH    13
Name: patient_state, dtype: int64
##################################################
445 PA     1
OH    20
Name: patient_state, dtype: int64
##################################################
446 MN     1
OH    27
Name: patient_state, dtype: int64
##################################################
447 OH    15
Name: patient_state, dtype: int64
##################################################
448 OH    25
Name: patient_state, dtype: int64
##################################################
449 OH    8
Name: patient_state, dtype: int64
##################################################
450 FL     1
OH    26
Name: patient_state, dtype: int64
##################################################
451 OH    14
Name: patient_state, dtype: int64
##################################################
452 OH    35
Name: patient_state, dtype: int64
##################################################
453 OH    42
Name: patient_state, dtype: int64
##################################################
454 OH    35
Name: patient_state, dtype: int64
##################################################
455 OH    5
Name: patient_state, dtype: int64
##################################################
456 OH    14
Name: patient_state, dtype: int64
##################################################
457 OH    12
Name: patient_state, dtype: int64
##################################################
458 OH    20
Name: patient_state, dtype: int64
##################################################
460 IN    32
Name: patient_state, dtype: int64
##################################################
461 IN    29
Name: patient_state, dtype: int64
##################################################
462 IN    59
Name: patient_state, dtype: int64
##################################################
463 IN    34
Name: patient_state, dtype: int64
##################################################
464 IN    7
Name: patient_state, dtype: int64
##################################################
465 IN    24
Name: patient_state, dtype: int64
##################################################
466 IN    6
Name: patient_state, dtype: int64
##################################################
467 IN    13
Name: patient_state, dtype: int64
##################################################
468 IN    13
Name: patient_state, dtype: int64
##################################################
469 IN    15
Name: patient_state, dtype: int64
##################################################
470 IN    8
Name: patient_state, dtype: int64
##################################################
471 KY     1
IN    17
Name: patient_state, dtype: int64
##################################################
472 IN    13
Name: patient_state, dtype: int64
##################################################
473 TX     1
IN    10
Name: patient_state, dtype: int64
##################################################
474 IN    11
Name: patient_state, dtype: int64
##################################################
475 IN    5
Name: patient_state, dtype: int64
##################################################
476 IN    2
Name: patient_state, dtype: int64
##################################################
477 KY    1
IN    2
Name: patient_state, dtype: int64
##################################################
478 IN    6
Name: patient_state, dtype: int64
##################################################
479 IN    10
Name: patient_state, dtype: int64
##################################################
480 MI    103
Name: patient_state, dtype: int64
##################################################
481 OH      1
MI    130
Name: patient_state, dtype: int64
##################################################
482 CA     2
MI    96
Name: patient_state, dtype: int64
##################################################
483 MI    95
Name: patient_state, dtype: int64
##################################################
484 MI    37
Name: patient_state, dtype: int64
##################################################
485 MS     1
MI    18
Name: patient_state, dtype: int64
##################################################
486 MI    28
Name: patient_state, dtype: int64
##################################################
487 MI    11
Name: patient_state, dtype: int64
##################################################
488 FL     1
MI    48
Name: patient_state, dtype: int64
##################################################
489 MI    10
Name: patient_state, dtype: int64
##################################################
490 IN     1
MI    56
Name: patient_state, dtype: int64
##################################################
491 CA    1
MI    7
Name: patient_state, dtype: int64
##################################################
492 MI    37
Name: patient_state, dtype: int64
##################################################
493 MI    34
Name: patient_state, dtype: int64
##################################################
494 MI    44
Name: patient_state, dtype: int64
##################################################
495 MI    36
Name: patient_state, dtype: int64
##################################################
496 MI    21
Name: patient_state, dtype: int64
##################################################
497 MI    18
Name: patient_state, dtype: int64
##################################################
498 MI    19
Name: patient_state, dtype: int64
##################################################
499 MI    7
Name: patient_state, dtype: int64
##################################################
500 IA    4
Name: patient_state, dtype: int64
##################################################
501 IA    4
Name: patient_state, dtype: int64
##################################################
502 IA    3
Name: patient_state, dtype: int64
##################################################
503 IA    7
Name: patient_state, dtype: int64
##################################################
504 IA    8
Name: patient_state, dtype: int64
##################################################
505 IA    6
Name: patient_state, dtype: int64
##################################################
506 IA    1
Name: patient_state, dtype: int64
##################################################
507 IA    4
Name: patient_state, dtype: int64
##################################################
510 IA    2
Name: patient_state, dtype: int64
##################################################
511 IA    5
Name: patient_state, dtype: int64
##################################################
512 IA    1
Name: patient_state, dtype: int64
##################################################
514 IA    1
Name: patient_state, dtype: int64
##################################################
515 IA    3
Name: patient_state, dtype: int64
##################################################
516 IA    2
Name: patient_state, dtype: int64
##################################################
520 IA    5
Name: patient_state, dtype: int64
##################################################
522 IA    7
Name: patient_state, dtype: int64
##################################################
523 IA    4
Name: patient_state, dtype: int64
##################################################
524 IA    5
Name: patient_state, dtype: int64
##################################################
525 IA    5
Name: patient_state, dtype: int64
##################################################
526 IA    1
Name: patient_state, dtype: int64
##################################################
527 IA    4
Name: patient_state, dtype: int64
##################################################
528 IA    4
Name: patient_state, dtype: int64
##################################################
530 WI    19
Name: patient_state, dtype: int64
##################################################
531 WI    37
Name: patient_state, dtype: int64
##################################################
532 TX     1
WI    20
Name: patient_state, dtype: int64
##################################################
534 WI    2
Name: patient_state, dtype: int64
##################################################
535 WI    24
Name: patient_state, dtype: int64
##################################################
537 WI    8
Name: patient_state, dtype: int64
##################################################
539 WI    5
Name: patient_state, dtype: int64
##################################################
540 WI    2
Name: patient_state, dtype: int64
##################################################
541 WI    13
Name: patient_state, dtype: int64
##################################################
542 WI    15
Name: patient_state, dtype: int64
##################################################
543 WI    7
Name: patient_state, dtype: int64
##################################################
544 WI    5
Name: patient_state, dtype: int64
##################################################
545 WI    3
Name: patient_state, dtype: int64
##################################################
546 WI    4
Name: patient_state, dtype: int64
##################################################
547 WI    7
Name: patient_state, dtype: int64
##################################################
548 WI    5
Name: patient_state, dtype: int64
##################################################
549 WI    32
Name: patient_state, dtype: int64
##################################################
550 MN    47
Name: patient_state, dtype: int64
##################################################
551 MN    39
Name: patient_state, dtype: int64
##################################################
553 WI     1
MN    62
Name: patient_state, dtype: int64
##################################################
554 MN    47
Name: patient_state, dtype: int64
##################################################
557 MN    13
Name: patient_state, dtype: int64
##################################################
558 MN    7
Name: patient_state, dtype: int64
##################################################
559 WI     1
MN    25
Name: patient_state, dtype: int64
##################################################
560 MN    37
Name: patient_state, dtype: int64
##################################################
561 MN    7
Name: patient_state, dtype: int64
##################################################
562 MN    19
Name: patient_state, dtype: int64
##################################################
563 MN    24
Name: patient_state, dtype: int64
##################################################
564 MN    10
Name: patient_state, dtype: int64
##################################################
565 MN    23
Name: patient_state, dtype: int64
##################################################
566 MN    6
Name: patient_state, dtype: int64
##################################################
567 MN    7
Name: patient_state, dtype: int64
##################################################
570 SD    2
Name: patient_state, dtype: int64
##################################################
573 SD    1
Name: patient_state, dtype: int64
##################################################
574 SD    1
Name: patient_state, dtype: int64
##################################################
577 SD    4
Name: patient_state, dtype: int64
##################################################
581 ND    3
Name: patient_state, dtype: int64
##################################################
582 ND    1
Name: patient_state, dtype: int64
##################################################
585 ND    1
Name: patient_state, dtype: int64
##################################################
587 ND    1
Name: patient_state, dtype: int64
##################################################
590 MT    2
Name: patient_state, dtype: int64
##################################################
591 MT    10
Name: patient_state, dtype: int64
##################################################
592 MT    1
Name: patient_state, dtype: int64
##################################################
593 MT    2
Name: patient_state, dtype: int64
##################################################
594 MT    6
Name: patient_state, dtype: int64
##################################################
596 MT    3
Name: patient_state, dtype: int64
##################################################
597 MT    6
Name: patient_state, dtype: int64
##################################################
598 MT    5
Name: patient_state, dtype: int64
##################################################
599 MT    9
Name: patient_state, dtype: int64
##################################################
600 OH      1
IL    103
Name: patient_state, dtype: int64
##################################################
601 WI     1
CT     1
IL    90
Name: patient_state, dtype: int64
##################################################
602 IL    9
Name: patient_state, dtype: int64
##################################################
603 IL    7
Name: patient_state, dtype: int64
##################################################
604 IL    96
Name: patient_state, dtype: int64
##################################################
605 FL     1
IL    99
Name: patient_state, dtype: int64
##################################################
606 MI      1
IL    149
Name: patient_state, dtype: int64
##################################################
607 IL    7
Name: patient_state, dtype: int64
##################################################
608 IL    2
Name: patient_state, dtype: int64
##################################################
609 IL    13
Name: patient_state, dtype: int64
##################################################
610 IL    15
Name: patient_state, dtype: int64
##################################################
611 IL    10
Name: patient_state, dtype: int64
##################################################
612 IL    11
Name: patient_state, dtype: int64
##################################################
613 IL    9
Name: patient_state, dtype: int64
##################################################
614 IL    6
Name: patient_state, dtype: int64
##################################################
615 IL    14
Name: patient_state, dtype: int64
##################################################
616 IL    9
Name: patient_state, dtype: int64
##################################################
617 IL    18
Name: patient_state, dtype: int64
##################################################
618 IL    11
Name: patient_state, dtype: int64
##################################################
619 IL    7
Name: patient_state, dtype: int64
##################################################
620 IL    7
Name: patient_state, dtype: int64
##################################################
622 IL    18
Name: patient_state, dtype: int64
##################################################
623 IL    2
Name: patient_state, dtype: int64
##################################################
624 IL    6
Name: patient_state, dtype: int64
##################################################
625 IL    14
Name: patient_state, dtype: int64
##################################################
626 IL    16
Name: patient_state, dtype: int64
##################################################
627 IL    11
Name: patient_state, dtype: int64
##################################################
628 IL    10
Name: patient_state, dtype: int64
##################################################
629 IL    11
Name: patient_state, dtype: int64
##################################################
630 MO    24
Name: patient_state, dtype: int64
##################################################
631 MO    33
Name: patient_state, dtype: int64
##################################################
633 MO    10
Name: patient_state, dtype: int64
##################################################
634 MO    1
Name: patient_state, dtype: int64
##################################################
635 MO    1
Name: patient_state, dtype: int64
##################################################
636 MO    5
Name: patient_state, dtype: int64
##################################################
637 MO    2
Name: patient_state, dtype: int64
##################################################
638 MO    4
Name: patient_state, dtype: int64
##################################################
639 MO    5
Name: patient_state, dtype: int64
##################################################
640 MO    14
Name: patient_state, dtype: int64
##################################################
641 MO    18
Name: patient_state, dtype: int64
##################################################
646 MO    2
Name: patient_state, dtype: int64
##################################################
647 MO    2
Name: patient_state, dtype: int64
##################################################
648 MO    5
Name: patient_state, dtype: int64
##################################################
650 MO    2
Name: patient_state, dtype: int64
##################################################
651 MO    1
Name: patient_state, dtype: int64
##################################################
652 MO    5
Name: patient_state, dtype: int64
##################################################
654 MO    3
Name: patient_state, dtype: int64
##################################################
655 MO    2
Name: patient_state, dtype: int64
##################################################
656 MO    6
Name: patient_state, dtype: int64
##################################################
657 MO    8
Name: patient_state, dtype: int64
##################################################
658 MO    7
Name: patient_state, dtype: int64
##################################################
660 KS    12
Name: patient_state, dtype: int64
##################################################
661 KS    4
Name: patient_state, dtype: int64
##################################################
662 KS    6
Name: patient_state, dtype: int64
##################################################
664 KS    1
Name: patient_state, dtype: int64
##################################################
665 KS    2
Name: patient_state, dtype: int64
##################################################
666 KS    4
Name: patient_state, dtype: int64
##################################################
668 KS    1
Name: patient_state, dtype: int64
##################################################
670 KS    3
Name: patient_state, dtype: int64
##################################################
671 KS    2
Name: patient_state, dtype: int64
##################################################
672 KS    11
Name: patient_state, dtype: int64
##################################################
675 KS    2
Name: patient_state, dtype: int64
##################################################
678 KS    1
Name: patient_state, dtype: int64
##################################################
679 KS    1
Name: patient_state, dtype: int64
##################################################
680 NE    7
Name: patient_state, dtype: int64
##################################################
681 NE    15
Name: patient_state, dtype: int64
##################################################
684 NE    3
Name: patient_state, dtype: int64
##################################################
685 NE    3
Name: patient_state, dtype: int64
##################################################
686 NE    2
Name: patient_state, dtype: int64
##################################################
687 NE    2
Name: patient_state, dtype: int64
##################################################
688 NE    1
Name: patient_state, dtype: int64
##################################################
689 NE    3
Name: patient_state, dtype: int64
##################################################
691 NE    3
Name: patient_state, dtype: int64
##################################################
693 NE    1
Name: patient_state, dtype: int64
##################################################
700 LA    18
Name: patient_state, dtype: int64
##################################################
701 TX     2
LA    23
Name: patient_state, dtype: int64
##################################################
703 LA    3
Name: patient_state, dtype: int64
##################################################
704 LA    16
Name: patient_state, dtype: int64
##################################################
705 LA    16
Name: patient_state, dtype: int64
##################################################
706 LA    10
Name: patient_state, dtype: int64
##################################################
707 LA    9
Name: patient_state, dtype: int64
##################################################
708 LA    6
Name: patient_state, dtype: int64
##################################################
710 LA    7
Name: patient_state, dtype: int64
##################################################
711 LA    9
Name: patient_state, dtype: int64
##################################################
712 LA    11
Name: patient_state, dtype: int64
##################################################
713 LA    4
Name: patient_state, dtype: int64
##################################################
714 LA    6
Name: patient_state, dtype: int64
##################################################
716 AR    4
Name: patient_state, dtype: int64
##################################################
718 AR    4
Name: patient_state, dtype: int64
##################################################
719 AR    5
Name: patient_state, dtype: int64
##################################################
720 AR    8
Name: patient_state, dtype: int64
##################################################
721 AR    6
Name: patient_state, dtype: int64
##################################################
722 MI    1
AR    3
Name: patient_state, dtype: int64
##################################################
723 AR    9
Name: patient_state, dtype: int64
##################################################
724 AR    1
Name: patient_state, dtype: int64
##################################################
725 AR    1
Name: patient_state, dtype: int64
##################################################
726 AR    3
Name: patient_state, dtype: int64
##################################################
727 AR    12
Name: patient_state, dtype: int64
##################################################
728 AR    2
Name: patient_state, dtype: int64
##################################################
729 NM    1
FL    1
AR    4
Name: patient_state, dtype: int64
##################################################
730 OK    20
Name: patient_state, dtype: int64
##################################################
731 OK    19
Name: patient_state, dtype: int64
##################################################
735 OK    2
Name: patient_state, dtype: int64
##################################################
737 OK    3
Name: patient_state, dtype: int64
##################################################
738 OK    1
Name: patient_state, dtype: int64
##################################################
740 OK    16
Name: patient_state, dtype: int64
##################################################
741 TX    1
OK    7
Name: patient_state, dtype: int64
##################################################
743 OK    2
Name: patient_state, dtype: int64
##################################################
744 OK    7
Name: patient_state, dtype: int64
##################################################
745 OK    3
Name: patient_state, dtype: int64
##################################################
746 OK    2
Name: patient_state, dtype: int64
##################################################
747 OK    2
Name: patient_state, dtype: int64
##################################################
748 OK    5
Name: patient_state, dtype: int64
##################################################
749 OK    3
Name: patient_state, dtype: int64
##################################################
750 TX    96
Name: patient_state, dtype: int64
##################################################
751 TX    25
Name: patient_state, dtype: int64
##################################################
752 TX    47
Name: patient_state, dtype: int64
##################################################
754 TX    9
Name: patient_state, dtype: int64
##################################################
755 TX    6
Name: patient_state, dtype: int64
##################################################
756 TX    8
Name: patient_state, dtype: int64
##################################################
757 TX    12
Name: patient_state, dtype: int64
##################################################
758 TX    3
Name: patient_state, dtype: int64
##################################################
759 TX    11
Name: patient_state, dtype: int64
##################################################
760 TX    59
Name: patient_state, dtype: int64
##################################################
761 TX    38
Name: patient_state, dtype: int64
##################################################
762 TX    19
Name: patient_state, dtype: int64
##################################################
763 TX    9
Name: patient_state, dtype: int64
##################################################
764 TX    4
Name: patient_state, dtype: int64
##################################################
765 TX    11
Name: patient_state, dtype: int64
##################################################
766 TX    9
Name: patient_state, dtype: int64
##################################################
767 TX    5
Name: patient_state, dtype: int64
##################################################
768 TX    2
Name: patient_state, dtype: int64
##################################################
769 TX    7
Name: patient_state, dtype: int64
##################################################
770 NJ      1
TX    131
Name: patient_state, dtype: int64
##################################################
772 TX    3
Name: patient_state, dtype: int64
##################################################
773 NJ     1
TX    58
Name: patient_state, dtype: int64
##################################################
774 TX    53
Name: patient_state, dtype: int64
##################################################
775 TX    58
Name: patient_state, dtype: int64
##################################################
776 TX    11
Name: patient_state, dtype: int64
##################################################
777 TX    4
Name: patient_state, dtype: int64
##################################################
778 TX    19
Name: patient_state, dtype: int64
##################################################
779 TX    5
Name: patient_state, dtype: int64
##################################################
780 TX    22
Name: patient_state, dtype: int64
##################################################
781 TX    13
Name: patient_state, dtype: int64
##################################################
782 TX    72
Name: patient_state, dtype: int64
##################################################
783 TX    10
Name: patient_state, dtype: int64
##################################################
784 TX    17
Name: patient_state, dtype: int64
##################################################
785 TX    49
Name: patient_state, dtype: int64
##################################################
786 KY     1
TX    29
Name: patient_state, dtype: int64
##################################################
787 TX    41
Name: patient_state, dtype: int64
##################################################
788 TX    10
Name: patient_state, dtype: int64
##################################################
789 TX    4
Name: patient_state, dtype: int64
##################################################
790 TX    17
Name: patient_state, dtype: int64
##################################################
791 TX    20
Name: patient_state, dtype: int64
##################################################
792 TX    1
Name: patient_state, dtype: int64
##################################################
793 TX    15
Name: patient_state, dtype: int64
##################################################
794 TX    25
Name: patient_state, dtype: int64
##################################################
795 TX    2
Name: patient_state, dtype: int64
##################################################
796 TX    2
Name: patient_state, dtype: int64
##################################################
797 TX    19
Name: patient_state, dtype: int64
##################################################
798 TX    7
Name: patient_state, dtype: int64
##################################################
799 TX    40
Name: patient_state, dtype: int64
##################################################
800 NH     1
CO    63
Name: patient_state, dtype: int64
##################################################
801 CO    68
Name: patient_state, dtype: int64
##################################################
802 CO    78
Name: patient_state, dtype: int64
##################################################
803 CO    10
Name: patient_state, dtype: int64
##################################################
804 CO    22
Name: patient_state, dtype: int64
##################################################
805 CO    24
Name: patient_state, dtype: int64
##################################################
806 CO    10
Name: patient_state, dtype: int64
##################################################
807 CO    1
Name: patient_state, dtype: int64
##################################################
808 CO    10
Name: patient_state, dtype: int64
##################################################
809 VA     1
CO    30
Name: patient_state, dtype: int64
##################################################
810 CO    7
Name: patient_state, dtype: int64
##################################################
811 CO    5
Name: patient_state, dtype: int64
##################################################
812 CO    3
Name: patient_state, dtype: int64
##################################################
813 CO    3
Name: patient_state, dtype: int64
##################################################
814 CO    9
Name: patient_state, dtype: int64
##################################################
815 CO    13
Name: patient_state, dtype: int64
##################################################
816 CO    9
Name: patient_state, dtype: int64
##################################################
826 WY    2
Name: patient_state, dtype: int64
##################################################
827 WY    1
Name: patient_state, dtype: int64
##################################################
828 WY    1
Name: patient_state, dtype: int64
##################################################
832 ID    10
Name: patient_state, dtype: int64
##################################################
833 ID    10
Name: patient_state, dtype: int64
##################################################
834 ID    10
Name: patient_state, dtype: int64
##################################################
835 ID    1
Name: patient_state, dtype: int64
##################################################
836 AZ     1
ID    30
Name: patient_state, dtype: int64
##################################################
837 ID    18
Name: patient_state, dtype: int64
##################################################
838 ID    13
Name: patient_state, dtype: int64
##################################################
840 UT    12
Name: patient_state, dtype: int64
##################################################
841 UT    11
Name: patient_state, dtype: int64
##################################################
844 TX    1
UT    5
Name: patient_state, dtype: int64
##################################################
846 UT    3
Name: patient_state, dtype: int64
##################################################
847 UT    4
Name: patient_state, dtype: int64
##################################################
850 DE     1
CO     2
AZ    48
Name: patient_state, dtype: int64
##################################################
851 AZ    10
Name: patient_state, dtype: int64
##################################################
852 MN     1
AZ    57
Name: patient_state, dtype: int64
##################################################
853 NY     1
NV     1
WI     1
AZ    47
Name: patient_state, dtype: int64
##################################################
855 AZ    2
Name: patient_state, dtype: int64
##################################################
856 AZ    12
Name: patient_state, dtype: int64
##################################################
857 AZ    38
Name: patient_state, dtype: int64
##################################################
859 AZ    2
Name: patient_state, dtype: int64
##################################################
860 AZ    1
Name: patient_state, dtype: int64
##################################################
863 AZ    5
Name: patient_state, dtype: int64
##################################################
864 AZ    1
Name: patient_state, dtype: int64
##################################################
870 CA     1
NM    17
Name: patient_state, dtype: int64
##################################################
871 OR     1
TX     2
NM    55
Name: patient_state, dtype: int64
##################################################
873 NM    3
Name: patient_state, dtype: int64
##################################################
874 NM    5
Name: patient_state, dtype: int64
##################################################
875 CO     1
NM    23
Name: patient_state, dtype: int64
##################################################
877 NM    6
Name: patient_state, dtype: int64
##################################################
880 NM    13
Name: patient_state, dtype: int64
##################################################
881 NM    1
Name: patient_state, dtype: int64
##################################################
882 NM    11
Name: patient_state, dtype: int64
##################################################
883 TX    1
NM    5
Name: patient_state, dtype: int64
##################################################
890 NV    12
Name: patient_state, dtype: int64
##################################################
891 NV    30
Name: patient_state, dtype: int64
##################################################
894 NV    10
Name: patient_state, dtype: int64
##################################################
895 NV    7
Name: patient_state, dtype: int64
##################################################
897 NV    1
Name: patient_state, dtype: int64
##################################################
900 WA      1
AZ      1
GA      1
OR      2
CA    232
Name: patient_state, dtype: int64
##################################################
902 GA      1
CA    114
Name: patient_state, dtype: int64
##################################################
903 CA    5
Name: patient_state, dtype: int64
##################################################
904 CA    5
Name: patient_state, dtype: int64
##################################################
905 CA    16
Name: patient_state, dtype: int64
##################################################
906 CA    72
Name: patient_state, dtype: int64
##################################################
907 CA    63
Name: patient_state, dtype: int64
##################################################
908 WA     1
CA    35
Name: patient_state, dtype: int64
##################################################
910 CA    32
Name: patient_state, dtype: int64
##################################################
911 FL     1
CA    20
Name: patient_state, dtype: int64
##################################################
912 CA    30
Name: patient_state, dtype: int64
##################################################
913 AZ      1
FL      2
CA    122
Name: patient_state, dtype: int64
##################################################
914 CA    23
Name: patient_state, dtype: int64
##################################################
915 CA    10
Name: patient_state, dtype: int64
##################################################
916 CA    17
Name: patient_state, dtype: int64
##################################################
917 AZ      1
CA    169
Name: patient_state, dtype: int64
##################################################
918 CA    11
Name: patient_state, dtype: int64
##################################################
919 CA    25
Name: patient_state, dtype: int64
##################################################
920 CA    79
Name: patient_state, dtype: int64
##################################################
921 CA    49
Name: patient_state, dtype: int64
##################################################
922 CA    49
Name: patient_state, dtype: int64
##################################################
923 GA      1
NV      1
CA    101
Name: patient_state, dtype: int64
##################################################
924 CA    18
Name: patient_state, dtype: int64
##################################################
925 OR     1
CA    85
Name: patient_state, dtype: int64
##################################################
926 CA    118
Name: patient_state, dtype: int64
##################################################
927 NJ     1
CA    32
Name: patient_state, dtype: int64
##################################################
928 ID     1
UT     1
CA    94
Name: patient_state, dtype: int64
##################################################
930 CA    34
Name: patient_state, dtype: int64
##################################################
931 CA    13
Name: patient_state, dtype: int64
##################################################
932 CA    38
Name: patient_state, dtype: int64
##################################################
933 CA    24
Name: patient_state, dtype: int64
##################################################
934 CA    31
Name: patient_state, dtype: int64
##################################################
935 CA    36
Name: patient_state, dtype: int64
##################################################
936 CA    36
Name: patient_state, dtype: int64
##################################################
937 CA    23
Name: patient_state, dtype: int64
##################################################
939 CA    27
Name: patient_state, dtype: int64
##################################################
940 CA    34
Name: patient_state, dtype: int64
##################################################
941 CA    37
Name: patient_state, dtype: int64
##################################################
943 CA    4
Name: patient_state, dtype: int64
##################################################
944 CA    3
Name: patient_state, dtype: int64
##################################################
945 MN     1
CA    67
Name: patient_state, dtype: int64
##################################################
946 CA    21
Name: patient_state, dtype: int64
##################################################
947 CA    9
Name: patient_state, dtype: int64
##################################################
948 CA    6
Name: patient_state, dtype: int64
##################################################
949 TX     1
CO     1
CA    19
Name: patient_state, dtype: int64
##################################################
950 CA    50
Name: patient_state, dtype: int64
##################################################
951 CA    29
Name: patient_state, dtype: int64
##################################################
952 CA    23
Name: patient_state, dtype: int64
##################################################
953 WA     1
CA    48
Name: patient_state, dtype: int64
##################################################
954 CA    18
Name: patient_state, dtype: int64
##################################################
955 CA    13
Name: patient_state, dtype: int64
##################################################
956 CA    55
Name: patient_state, dtype: int64
##################################################
957 CA    11
Name: patient_state, dtype: int64
##################################################
958 CA    35
Name: patient_state, dtype: int64
##################################################
959 WA     1
CA    40
Name: patient_state, dtype: int64
##################################################
960 CA    16
Name: patient_state, dtype: int64
##################################################
961 CA    5
Name: patient_state, dtype: int64
##################################################
967 HI    12
Name: patient_state, dtype: int64
##################################################
968 TN    1
HI    9
Name: patient_state, dtype: int64
##################################################
970 AZ     1
OR    11
Name: patient_state, dtype: int64
##################################################
971 OR    9
Name: patient_state, dtype: int64
##################################################
972 OR    15
Name: patient_state, dtype: int64
##################################################
973 OR    12
Name: patient_state, dtype: int64
##################################################
974 OR    19
Name: patient_state, dtype: int64
##################################################
975 OR    12
Name: patient_state, dtype: int64
##################################################
976 OR    2
Name: patient_state, dtype: int64
##################################################
977 OR    1
Name: patient_state, dtype: int64
##################################################
978 OR    2
Name: patient_state, dtype: int64
##################################################
980 OR     1
TX     1
NM     1
WA    45
Name: patient_state, dtype: int64
##################################################
981 WA    27
Name: patient_state, dtype: int64
##################################################
982 WA    27
Name: patient_state, dtype: int64
##################################################
983 WA    19
Name: patient_state, dtype: int64
##################################################
984 TX     1
WA    14
Name: patient_state, dtype: int64
##################################################
985 WA    5
Name: patient_state, dtype: int64
##################################################
986 WA    12
Name: patient_state, dtype: int64
##################################################
988 OR    1
WA    9
Name: patient_state, dtype: int64
##################################################
989 WA    3
Name: patient_state, dtype: int64
##################################################
990 WA    7
Name: patient_state, dtype: int64
##################################################
991 OH    1
WA    8
Name: patient_state, dtype: int64
##################################################
992 WA    12
Name: patient_state, dtype: int64
##################################################
993 WA    6
Name: patient_state, dtype: int64
##################################################
994 WA    1
Name: patient_state, dtype: int64
##################################################
995 AK    2
Name: patient_state, dtype: int64
##################################################
996 AK    2
Name: patient_state, dtype: int64
##################################################
998 AK    1
Name: patient_state, dtype: int64
##################################################
999 AK    1
Name: patient_state, dtype: int64
In [36]:
test["patient_state"] = test.apply(lambda row: stocker.get(row["patient_zip3"], row["patient_state"]), axis=1)
In [37]:
test.loc[5773 , "patient_state"] = "Missouri"
In [38]:
for zp in patient_zip3 : 
    stocker[zp] = train[train['patient_zip3'] == zp].patient_state.value_counts().sort_values().index[-1]
    print("#"*50)
    print(zp , train[train['patient_zip3'] == zp].patient_state.value_counts().sort_values())
##################################################
101 NY    2
Name: patient_state, dtype: int64
##################################################
103 NY    35
Name: patient_state, dtype: int64
##################################################
104 NY    112
Name: patient_state, dtype: int64
##################################################
105 NY    33
Name: patient_state, dtype: int64
##################################################
106 NY    5
Name: patient_state, dtype: int64
##################################################
107 NY    11
Name: patient_state, dtype: int64
##################################################
108 NY    7
Name: patient_state, dtype: int64
##################################################
109 NY    18
Name: patient_state, dtype: int64
##################################################
110 NY    15
Name: patient_state, dtype: int64
##################################################
111 NY    14
Name: patient_state, dtype: int64
##################################################
112 NY    192
Name: patient_state, dtype: int64
##################################################
113 NY    71
Name: patient_state, dtype: int64
##################################################
114 NY    57
Name: patient_state, dtype: int64
##################################################
115 NY    40
Name: patient_state, dtype: int64
##################################################
116 NY    8
Name: patient_state, dtype: int64
##################################################
117 NY    72
Name: patient_state, dtype: int64
##################################################
118 AZ    2
Name: patient_state, dtype: int64
##################################################
119 NY    14
Name: patient_state, dtype: int64
##################################################
120 NY    27
Name: patient_state, dtype: int64
##################################################
121 NY    25
Name: patient_state, dtype: int64
##################################################
122 NY    14
Name: patient_state, dtype: int64
##################################################
123 NY    14
Name: patient_state, dtype: int64
##################################################
124 NY    11
Name: patient_state, dtype: int64
##################################################
125 NY    24
Name: patient_state, dtype: int64
##################################################
126 NY    3
Name: patient_state, dtype: int64
##################################################
127 NY    8
Name: patient_state, dtype: int64
##################################################
128 NY    19
Name: patient_state, dtype: int64
##################################################
129 NY    4
Name: patient_state, dtype: int64
##################################################
130 NY    5
Name: patient_state, dtype: int64
##################################################
131 NY    2
Name: patient_state, dtype: int64
##################################################
132 NY    6
Name: patient_state, dtype: int64
##################################################
133 NY    3
Name: patient_state, dtype: int64
##################################################
134 NY    7
Name: patient_state, dtype: int64
##################################################
135 NY    2
Name: patient_state, dtype: int64
##################################################
136 NY    10
Name: patient_state, dtype: int64
##################################################
137 NY    4
Name: patient_state, dtype: int64
##################################################
138 NY    7
Name: patient_state, dtype: int64
##################################################
139 NY    1
Name: patient_state, dtype: int64
##################################################
140 NY    40
Name: patient_state, dtype: int64
##################################################
141 NY    25
Name: patient_state, dtype: int64
##################################################
142 NY    53
Name: patient_state, dtype: int64
##################################################
143 NY    6
Name: patient_state, dtype: int64
##################################################
144 NY    9
Name: patient_state, dtype: int64
##################################################
145 NY    11
Name: patient_state, dtype: int64
##################################################
146 NY    23
Name: patient_state, dtype: int64
##################################################
147 NY    8
Name: patient_state, dtype: int64
##################################################
148 NY    6
Name: patient_state, dtype: int64
##################################################
149 NY    1
Name: patient_state, dtype: int64
##################################################
150 PA    6
Name: patient_state, dtype: int64
##################################################
151 PA    11
Name: patient_state, dtype: int64
##################################################
152 PA    11
Name: patient_state, dtype: int64
##################################################
154 PA    2
Name: patient_state, dtype: int64
##################################################
155 PA    1
Name: patient_state, dtype: int64
##################################################
156 PA    9
Name: patient_state, dtype: int64
##################################################
157 PA    2
Name: patient_state, dtype: int64
##################################################
158 PA    2
Name: patient_state, dtype: int64
##################################################
159 PA    2
Name: patient_state, dtype: int64
##################################################
160 PA    5
Name: patient_state, dtype: int64
##################################################
161 PA    2
Name: patient_state, dtype: int64
##################################################
162 PA    1
Name: patient_state, dtype: int64
##################################################
163 PA    1
Name: patient_state, dtype: int64
##################################################
164 PA    4
Name: patient_state, dtype: int64
##################################################
165 PA    7
Name: patient_state, dtype: int64
##################################################
166 PA    3
Name: patient_state, dtype: int64
##################################################
168 PA    2
Name: patient_state, dtype: int64
##################################################
169 PA    2
Name: patient_state, dtype: int64
##################################################
170 PA    21
Name: patient_state, dtype: int64
##################################################
171 PA    7
Name: patient_state, dtype: int64
##################################################
172 PA    4
Name: patient_state, dtype: int64
##################################################
173 PA    10
Name: patient_state, dtype: int64
##################################################
174 PA    4
Name: patient_state, dtype: int64
##################################################
175 PA    9
Name: patient_state, dtype: int64
##################################################
176 PA    6
Name: patient_state, dtype: int64
##################################################
177 PA    7
Name: patient_state, dtype: int64
##################################################
178 PA    13
Name: patient_state, dtype: int64
##################################################
179 PA    6
Name: patient_state, dtype: int64
##################################################
180 PA    24
Name: patient_state, dtype: int64
##################################################
181 PA    10
Name: patient_state, dtype: int64
##################################################
182 PA    5
Name: patient_state, dtype: int64
##################################################
183 PA    15
Name: patient_state, dtype: int64
##################################################
184 PA    6
Name: patient_state, dtype: int64
##################################################
185 PA    5
Name: patient_state, dtype: int64
##################################################
186 PA    11
Name: patient_state, dtype: int64
##################################################
187 PA    3
Name: patient_state, dtype: int64
##################################################
189 PA    32
Name: patient_state, dtype: int64
##################################################
190 PA    64
Name: patient_state, dtype: int64
##################################################
191 PA    91
Name: patient_state, dtype: int64
##################################################
193 PA    18
Name: patient_state, dtype: int64
##################################################
194 PA    37
Name: patient_state, dtype: int64
##################################################
195 PA    3
Name: patient_state, dtype: int64
##################################################
196 PA    6
Name: patient_state, dtype: int64
##################################################
197 DE    7
Name: patient_state, dtype: int64
##################################################
198 DE    6
Name: patient_state, dtype: int64
##################################################
199 DE    16
Name: patient_state, dtype: int64
##################################################
200 DC    20
Name: patient_state, dtype: int64
##################################################
201 VA    23
Name: patient_state, dtype: int64
##################################################
206 MD    4
Name: patient_state, dtype: int64
##################################################
207 MD    11
Name: patient_state, dtype: int64
##################################################
208 MD    12
Name: patient_state, dtype: int64
##################################################
209 MD    4
Name: patient_state, dtype: int64
##################################################
210 MD    7
Name: patient_state, dtype: int64
##################################################
211 MD    8
Name: patient_state, dtype: int64
##################################################
212 MD    14
Name: patient_state, dtype: int64
##################################################
215 MD    3
Name: patient_state, dtype: int64
##################################################
216 MD    2
Name: patient_state, dtype: int64
##################################################
217 MD    8
Name: patient_state, dtype: int64
##################################################
220 VA    11
Name: patient_state, dtype: int64
##################################################
221 VA    15
Name: patient_state, dtype: int64
##################################################
222 VA    5
Name: patient_state, dtype: int64
##################################################
223 VA    6
Name: patient_state, dtype: int64
##################################################
224 VA    8
Name: patient_state, dtype: int64
##################################################
225 VA    6
Name: patient_state, dtype: int64
##################################################
226 VA    7
Name: patient_state, dtype: int64
##################################################
227 VA    6
Name: patient_state, dtype: int64
##################################################
228 VA    10
Name: patient_state, dtype: int64
##################################################
229 VA    16
Name: patient_state, dtype: int64
##################################################
230 VA    16
Name: patient_state, dtype: int64
##################################################
231 VA    17
Name: patient_state, dtype: int64
##################################################
232 VA    28
Name: patient_state, dtype: int64
##################################################
233 VA    20
Name: patient_state, dtype: int64
##################################################
234 VA    30
Name: patient_state, dtype: int64
##################################################
235 VA    14
Name: patient_state, dtype: int64
##################################################
236 VA    21
Name: patient_state, dtype: int64
##################################################
237 VA    3
Name: patient_state, dtype: int64
##################################################
238 VA    25
Name: patient_state, dtype: int64
##################################################
239 VA    9
Name: patient_state, dtype: int64
##################################################
240 VA    17
Name: patient_state, dtype: int64
##################################################
241 VA    11
Name: patient_state, dtype: int64
##################################################
242 VA    7
Name: patient_state, dtype: int64
##################################################
243 VA    6
Name: patient_state, dtype: int64
##################################################
244 VA    7
Name: patient_state, dtype: int64
##################################################
245 VA    18
Name: patient_state, dtype: int64
##################################################
246 VA    5
Name: patient_state, dtype: int64
##################################################
247 WV    1
Name: patient_state, dtype: int64
##################################################
248 WV    3
Name: patient_state, dtype: int64
##################################################
251 WV    1
Name: patient_state, dtype: int64
##################################################
252 WV    1
Name: patient_state, dtype: int64
##################################################
253 WV    2
Name: patient_state, dtype: int64
##################################################
254 WV    2
Name: patient_state, dtype: int64
##################################################
255 WV    1
Name: patient_state, dtype: int64
##################################################
256 WV    1
Name: patient_state, dtype: int64
##################################################
259 WV    2
Name: patient_state, dtype: int64
##################################################
260 WV    3
Name: patient_state, dtype: int64
##################################################
261 WV    1
Name: patient_state, dtype: int64
##################################################
262 WV    3
Name: patient_state, dtype: int64
##################################################
263 WV    1
Name: patient_state, dtype: int64
##################################################
264 WV    1
Name: patient_state, dtype: int64
##################################################
265 WV    1
Name: patient_state, dtype: int64
##################################################
267 WV    3
Name: patient_state, dtype: int64
##################################################
270 NC    7
Name: patient_state, dtype: int64
##################################################
271 NC    9
Name: patient_state, dtype: int64
##################################################
272 NC    12
Name: patient_state, dtype: int64
##################################################
273 NC    4
Name: patient_state, dtype: int64
##################################################
274 NC    5
Name: patient_state, dtype: int64
##################################################
275 NC    23
Name: patient_state, dtype: int64
##################################################
276 NC    9
Name: patient_state, dtype: int64
##################################################
277 NC    4
Name: patient_state, dtype: int64
##################################################
278 NC    11
Name: patient_state, dtype: int64
##################################################
279 NC    5
Name: patient_state, dtype: int64
##################################################
280 NC    16
Name: patient_state, dtype: int64
##################################################
281 NC    7
Name: patient_state, dtype: int64
##################################################
282 NC    20
Name: patient_state, dtype: int64
##################################################
283 NC    14
Name: patient_state, dtype: int64
##################################################
284 NC    9
Name: patient_state, dtype: int64
##################################################
285 NC    6
Name: patient_state, dtype: int64
##################################################
286 NC    8
Name: patient_state, dtype: int64
##################################################
287 NC    11
Name: patient_state, dtype: int64
##################################################
288 NC    2
Name: patient_state, dtype: int64
##################################################
290 SC    12
Name: patient_state, dtype: int64
##################################################
291 SC    10
Name: patient_state, dtype: int64
##################################################
292 SC    8
Name: patient_state, dtype: int64
##################################################
293 SC    7
Name: patient_state, dtype: int64
##################################################
294 SC    15
Name: patient_state, dtype: int64
##################################################
295 SC    11
Name: patient_state, dtype: int64
##################################################
296 SC    21
Name: patient_state, dtype: int64
##################################################
297 SC    13
Name: patient_state, dtype: int64
##################################################
298 SC    7
Name: patient_state, dtype: int64
##################################################
299 SC    6
Name: patient_state, dtype: int64
##################################################
300 GA    121
Name: patient_state, dtype: int64
##################################################
301 GA    59
Name: patient_state, dtype: int64
##################################################
302 GA    53
Name: patient_state, dtype: int64
##################################################
303 GA    48
Name: patient_state, dtype: int64
##################################################
304 GA    13
Name: patient_state, dtype: int64
##################################################
305 GA    33
Name: patient_state, dtype: int64
##################################################
306 GA    25
Name: patient_state, dtype: int64
##################################################
307 GA    15
Name: patient_state, dtype: int64
##################################################
308 GA    7
Name: patient_state, dtype: int64
##################################################
309 GA    13
Name: patient_state, dtype: int64
##################################################
310 GA    28
Name: patient_state, dtype: int64
##################################################
312 GA    6
Name: patient_state, dtype: int64
##################################################
313 GA    10
Name: patient_state, dtype: int64
##################################################
314 GA    22
Name: patient_state, dtype: int64
##################################################
315 GA    27
Name: patient_state, dtype: int64
##################################################
316 GA    14
Name: patient_state, dtype: int64
##################################################
317 GA    35
Name: patient_state, dtype: int64
##################################################
318 GA    5
Name: patient_state, dtype: int64
##################################################
319 GA    9
Name: patient_state, dtype: int64
##################################################
320 FL    12
Name: patient_state, dtype: int64
##################################################
321 FL    15
Name: patient_state, dtype: int64
##################################################
322 FL    29
Name: patient_state, dtype: int64
##################################################
323 FL    7
Name: patient_state, dtype: int64
##################################################
324 FL    12
Name: patient_state, dtype: int64
##################################################
325 FL    9
Name: patient_state, dtype: int64
##################################################
326 FL    3
Name: patient_state, dtype: int64
##################################################
327 FL    19
Name: patient_state, dtype: int64
##################################################
328 FL    30
Name: patient_state, dtype: int64
##################################################
329 FL    15
Name: patient_state, dtype: int64
##################################################
330 FL    67
Name: patient_state, dtype: int64
##################################################
331 FL    92
Name: patient_state, dtype: int64
##################################################
332 FL    1
Name: patient_state, dtype: int64
##################################################
333 FL    20
Name: patient_state, dtype: int64
##################################################
334 FL    35
Name: patient_state, dtype: int64
##################################################
335 FL    23
Name: patient_state, dtype: int64
##################################################
336 FL    34
Name: patient_state, dtype: int64
##################################################
337 FL    30
Name: patient_state, dtype: int64
##################################################
338 FL    28
Name: patient_state, dtype: int64
##################################################
339 FL    23
Name: patient_state, dtype: int64
##################################################
341 FL    5
Name: patient_state, dtype: int64
##################################################
342 FL    33
Name: patient_state, dtype: int64
##################################################
344 FL    6
Name: patient_state, dtype: int64
##################################################
346 FL    26
Name: patient_state, dtype: int64
##################################################
347 FL    20
Name: patient_state, dtype: int64
##################################################
349 FL    15
Name: patient_state, dtype: int64
##################################################
350 AL    5
Name: patient_state, dtype: int64
##################################################
351 AL    1
Name: patient_state, dtype: int64
##################################################
352 AL    4
Name: patient_state, dtype: int64
##################################################
354 AL    2
Name: patient_state, dtype: int64
##################################################
356 AL    7
Name: patient_state, dtype: int64
##################################################
357 AL    5
Name: patient_state, dtype: int64
##################################################
358 AL    3
Name: patient_state, dtype: int64
##################################################
359 AL    4
Name: patient_state, dtype: int64
##################################################
360 AL    2
Name: patient_state, dtype: int64
##################################################
361 AL    1
Name: patient_state, dtype: int64
##################################################
363 AL    2
Name: patient_state, dtype: int64
##################################################
365 AL    6
Name: patient_state, dtype: int64
##################################################
366 AL    2
Name: patient_state, dtype: int64
##################################################
367 AL    1
Name: patient_state, dtype: int64
##################################################
368 AL    7
Name: patient_state, dtype: int64
##################################################
370 TN    16
Name: patient_state, dtype: int64
##################################################
371 TN    14
Name: patient_state, dtype: int64
##################################################
372 TN    3
Name: patient_state, dtype: int64
##################################################
373 TN    4
Name: patient_state, dtype: int64
##################################################
374 TN    3
Name: patient_state, dtype: int64
##################################################
376 TN    4
Name: patient_state, dtype: int64
##################################################
377 TN    7
Name: patient_state, dtype: int64
##################################################
378 TN    10
Name: patient_state, dtype: int64
##################################################
379 TN    4
Name: patient_state, dtype: int64
##################################################
380 TN    7
Name: patient_state, dtype: int64
##################################################
381 TN    21
Name: patient_state, dtype: int64
##################################################
382 TN    3
Name: patient_state, dtype: int64
##################################################
383 TN    6
Name: patient_state, dtype: int64
##################################################
384 TN    6
Name: patient_state, dtype: int64
##################################################
385 TN    5
Name: patient_state, dtype: int64
##################################################
386 MS    9
Name: patient_state, dtype: int64
##################################################
387 MS    4
Name: patient_state, dtype: int64
##################################################
388 MS    3
Name: patient_state, dtype: int64
##################################################
389 MS    3
Name: patient_state, dtype: int64
##################################################
390 MS    11
Name: patient_state, dtype: int64
##################################################
391 MS    12
Name: patient_state, dtype: int64
##################################################
392 MS    12
Name: patient_state, dtype: int64
##################################################
393 MS    2
Name: patient_state, dtype: int64
##################################################
394 MS    6
Name: patient_state, dtype: int64
##################################################
395 MS    8
Name: patient_state, dtype: int64
##################################################
396 MS    3
Name: patient_state, dtype: int64
##################################################
397 MS    1
Name: patient_state, dtype: int64
##################################################
398 GA    8
Name: patient_state, dtype: int64
##################################################
400 KY    20
Name: patient_state, dtype: int64
##################################################
401 KY    8
Name: patient_state, dtype: int64
##################################################
402 KY    45
Name: patient_state, dtype: int64
##################################################
403 KY    14
Name: patient_state, dtype: int64
##################################################
404 KY    15
Name: patient_state, dtype: int64
##################################################
405 KY    30
Name: patient_state, dtype: int64
##################################################
406 KY    3
Name: patient_state, dtype: int64
##################################################
407 KY    7
Name: patient_state, dtype: int64
##################################################
408 KY    2
Name: patient_state, dtype: int64
##################################################
409 KY    4
Name: patient_state, dtype: int64
##################################################
410 KY    23
Name: patient_state, dtype: int64
##################################################
411 KY    8
Name: patient_state, dtype: int64
##################################################
412 KY    2
Name: patient_state, dtype: int64
##################################################
413 KY    2
Name: patient_state, dtype: int64
##################################################
414 KY    2
Name: patient_state, dtype: int64
##################################################
415 KY    3
Name: patient_state, dtype: int64
##################################################
416 KY    1
Name: patient_state, dtype: int64
##################################################
417 KY    3
Name: patient_state, dtype: int64
##################################################
418 KY    3
Name: patient_state, dtype: int64
##################################################
420 KY    7
Name: patient_state, dtype: int64
##################################################
421 KY    13
Name: patient_state, dtype: int64
##################################################
422 KY    6
Name: patient_state, dtype: int64
##################################################
423 KY    13
Name: patient_state, dtype: int64
##################################################
424 KY    4
Name: patient_state, dtype: int64
##################################################
425 KY    3
Name: patient_state, dtype: int64
##################################################
426 KY    5
Name: patient_state, dtype: int64
##################################################
427 KY    11
Name: patient_state, dtype: int64
##################################################
430 OH    60
Name: patient_state, dtype: int64
##################################################
431 OH    26
Name: patient_state, dtype: int64
##################################################
432 OH    52
Name: patient_state, dtype: int64
##################################################
433 OH    9
Name: patient_state, dtype: int64
##################################################
434 OH    12
Name: patient_state, dtype: int64
##################################################
435 OH    18
Name: patient_state, dtype: int64
##################################################
436 OH    22
Name: patient_state, dtype: int64
##################################################
437 OH    13
Name: patient_state, dtype: int64
##################################################
438 OH    4
Name: patient_state, dtype: int64
##################################################
439 OH    7
Name: patient_state, dtype: int64
##################################################
440 OH    72
Name: patient_state, dtype: int64
##################################################
441 OH    74
Name: patient_state, dtype: int64
##################################################
442 OH    44
Name: patient_state, dtype: int64
##################################################
443 OH    26
Name: patient_state, dtype: int64
##################################################
444 OH    13
Name: patient_state, dtype: int64
##################################################
445 OH    21
Name: patient_state, dtype: int64
##################################################
446 OH    28
Name: patient_state, dtype: int64
##################################################
447 OH    15
Name: patient_state, dtype: int64
##################################################
448 OH    25
Name: patient_state, dtype: int64
##################################################
449 OH    8
Name: patient_state, dtype: int64
##################################################
450 OH    27
Name: patient_state, dtype: int64
##################################################
451 OH    14
Name: patient_state, dtype: int64
##################################################
452 OH    35
Name: patient_state, dtype: int64
##################################################
453 OH    42
Name: patient_state, dtype: int64
##################################################
454 OH    36
Name: patient_state, dtype: int64
##################################################
455 OH    5
Name: patient_state, dtype: int64
##################################################
456 OH    14
Name: patient_state, dtype: int64
##################################################
457 OH    12
Name: patient_state, dtype: int64
##################################################
458 OH    20
Name: patient_state, dtype: int64
##################################################
460 IN    32
Name: patient_state, dtype: int64
##################################################
461 IN    29
Name: patient_state, dtype: int64
##################################################
462 IN    59
Name: patient_state, dtype: int64
##################################################
463 IN    34
Name: patient_state, dtype: int64
##################################################
464 IN    7
Name: patient_state, dtype: int64
##################################################
465 IN    24
Name: patient_state, dtype: int64
##################################################
466 IN    6
Name: patient_state, dtype: int64
##################################################
467 IN    13
Name: patient_state, dtype: int64
##################################################
468 IN    13
Name: patient_state, dtype: int64
##################################################
469 IN    15
Name: patient_state, dtype: int64
##################################################
470 IN    8
Name: patient_state, dtype: int64
##################################################
471 IN    18
Name: patient_state, dtype: int64
##################################################
472 IN    13
Name: patient_state, dtype: int64
##################################################
473 IN    11
Name: patient_state, dtype: int64
##################################################
474 IN    11
Name: patient_state, dtype: int64
##################################################
475 IN    5
Name: patient_state, dtype: int64
##################################################
476 IN    2
Name: patient_state, dtype: int64
##################################################
477 IN    3
Name: patient_state, dtype: int64
##################################################
478 IN    6
Name: patient_state, dtype: int64
##################################################
479 IN    10
Name: patient_state, dtype: int64
##################################################
480 MI    103
Name: patient_state, dtype: int64
##################################################
481 MI    131
Name: patient_state, dtype: int64
##################################################
482 MI    98
Name: patient_state, dtype: int64
##################################################
483 MI    95
Name: patient_state, dtype: int64
##################################################
484 MI    37
Name: patient_state, dtype: int64
##################################################
485 MI    19
Name: patient_state, dtype: int64
##################################################
486 MI    28
Name: patient_state, dtype: int64
##################################################
487 MI    11
Name: patient_state, dtype: int64
##################################################
488 MI    49
Name: patient_state, dtype: int64
##################################################
489 MI    10
Name: patient_state, dtype: int64
##################################################
490 MI    57
Name: patient_state, dtype: int64
##################################################
491 MI    8
Name: patient_state, dtype: int64
##################################################
492 MI    37
Name: patient_state, dtype: int64
##################################################
493 MI    34
Name: patient_state, dtype: int64
##################################################
494 MI    44
Name: patient_state, dtype: int64
##################################################
495 MI    36
Name: patient_state, dtype: int64
##################################################
496 MI    21
Name: patient_state, dtype: int64
##################################################
497 MI    18
Name: patient_state, dtype: int64
##################################################
498 MI    19
Name: patient_state, dtype: int64
##################################################
499 MI    7
Name: patient_state, dtype: int64
##################################################
500 IA    4
Name: patient_state, dtype: int64
##################################################
501 IA    4
Name: patient_state, dtype: int64
##################################################
502 IA    3
Name: patient_state, dtype: int64
##################################################
503 IA    7
Name: patient_state, dtype: int64
##################################################
504 IA    8
Name: patient_state, dtype: int64
##################################################
505 IA    6
Name: patient_state, dtype: int64
##################################################
506 IA    1
Name: patient_state, dtype: int64
##################################################
507 IA    4
Name: patient_state, dtype: int64
##################################################
510 IA    2
Name: patient_state, dtype: int64
##################################################
511 IA    5
Name: patient_state, dtype: int64
##################################################
512 IA    1
Name: patient_state, dtype: int64
##################################################
514 IA    1
Name: patient_state, dtype: int64
##################################################
515 IA    3
Name: patient_state, dtype: int64
##################################################
516 IA    2
Name: patient_state, dtype: int64
##################################################
520 IA    5
Name: patient_state, dtype: int64
##################################################
522 IA    7
Name: patient_state, dtype: int64
##################################################
523 IA    4
Name: patient_state, dtype: int64
##################################################
524 IA    5
Name: patient_state, dtype: int64
##################################################
525 IA    5
Name: patient_state, dtype: int64
##################################################
526 IA    1
Name: patient_state, dtype: int64
##################################################
527 IA    4
Name: patient_state, dtype: int64
##################################################
528 IA    4
Name: patient_state, dtype: int64
##################################################
530 WI    19
Name: patient_state, dtype: int64
##################################################
531 WI    37
Name: patient_state, dtype: int64
##################################################
532 WI    21
Name: patient_state, dtype: int64
##################################################
534 WI    2
Name: patient_state, dtype: int64
##################################################
535 WI    24
Name: patient_state, dtype: int64
##################################################
537 WI    8
Name: patient_state, dtype: int64
##################################################
539 WI    5
Name: patient_state, dtype: int64
##################################################
540 WI    2
Name: patient_state, dtype: int64
##################################################
541 WI    13
Name: patient_state, dtype: int64
##################################################
542 WI    15
Name: patient_state, dtype: int64
##################################################
543 WI    7
Name: patient_state, dtype: int64
##################################################
544 WI    5
Name: patient_state, dtype: int64
##################################################
545 WI    3
Name: patient_state, dtype: int64
##################################################
546 WI    4
Name: patient_state, dtype: int64
##################################################
547 WI    7
Name: patient_state, dtype: int64
##################################################
548 WI    5
Name: patient_state, dtype: int64
##################################################
549 WI    32
Name: patient_state, dtype: int64
##################################################
550 MN    47
Name: patient_state, dtype: int64
##################################################
551 MN    39
Name: patient_state, dtype: int64
##################################################
553 MN    63
Name: patient_state, dtype: int64
##################################################
554 MN    47
Name: patient_state, dtype: int64
##################################################
557 MN    13
Name: patient_state, dtype: int64
##################################################
558 MN    7
Name: patient_state, dtype: int64
##################################################
559 MN    26
Name: patient_state, dtype: int64
##################################################
560 MN    37
Name: patient_state, dtype: int64
##################################################
561 MN    7
Name: patient_state, dtype: int64
##################################################
562 MN    19
Name: patient_state, dtype: int64
##################################################
563 MN    24
Name: patient_state, dtype: int64
##################################################
564 MN    10
Name: patient_state, dtype: int64
##################################################
565 MN    23
Name: patient_state, dtype: int64
##################################################
566 MN    6
Name: patient_state, dtype: int64
##################################################
567 MN    7
Name: patient_state, dtype: int64
##################################################
570 SD    2
Name: patient_state, dtype: int64
##################################################
573 SD    1
Name: patient_state, dtype: int64
##################################################
574 SD    1
Name: patient_state, dtype: int64
##################################################
577 SD    4
Name: patient_state, dtype: int64
##################################################
581 ND    3
Name: patient_state, dtype: int64
##################################################
582 ND    1
Name: patient_state, dtype: int64
##################################################
585 ND    1
Name: patient_state, dtype: int64
##################################################
587 ND    1
Name: patient_state, dtype: int64
##################################################
590 MT    2
Name: patient_state, dtype: int64
##################################################
591 MT    10
Name: patient_state, dtype: int64
##################################################
592 MT    1
Name: patient_state, dtype: int64
##################################################
593 MT    2
Name: patient_state, dtype: int64
##################################################
594 MT    6
Name: patient_state, dtype: int64
##################################################
596 MT    3
Name: patient_state, dtype: int64
##################################################
597 MT    6
Name: patient_state, dtype: int64
##################################################
598 MT    5
Name: patient_state, dtype: int64
##################################################
599 MT    9
Name: patient_state, dtype: int64
##################################################
600 IL    104
Name: patient_state, dtype: int64
##################################################
601 IL    94
Name: patient_state, dtype: int64
##################################################
602 IL    9
Name: patient_state, dtype: int64
##################################################
603 IL    7
Name: patient_state, dtype: int64
##################################################
604 IL    96
Name: patient_state, dtype: int64
##################################################
605 IL    100
Name: patient_state, dtype: int64
##################################################
606 IL    150
Name: patient_state, dtype: int64
##################################################
607 IL    7
Name: patient_state, dtype: int64
##################################################
608 IL    2
Name: patient_state, dtype: int64
##################################################
609 IL    13
Name: patient_state, dtype: int64
##################################################
610 IL    15
Name: patient_state, dtype: int64
##################################################
611 IL    10
Name: patient_state, dtype: int64
##################################################
612 IL    11
Name: patient_state, dtype: int64
##################################################
613 IL    9
Name: patient_state, dtype: int64
##################################################
614 IL    6
Name: patient_state, dtype: int64
##################################################
615 IL    14
Name: patient_state, dtype: int64
##################################################
616 IL    9
Name: patient_state, dtype: int64
##################################################
617 IL    18
Name: patient_state, dtype: int64
##################################################
618 IL    11
Name: patient_state, dtype: int64
##################################################
619 IL    7
Name: patient_state, dtype: int64
##################################################
620 IL    7
Name: patient_state, dtype: int64
##################################################
622 IL    18
Name: patient_state, dtype: int64
##################################################
623 IL    2
Name: patient_state, dtype: int64
##################################################
624 IL    6
Name: patient_state, dtype: int64
##################################################
625 IL    14
Name: patient_state, dtype: int64
##################################################
626 IL    16
Name: patient_state, dtype: int64
##################################################
627 IL    11
Name: patient_state, dtype: int64
##################################################
628 IL    10
Name: patient_state, dtype: int64
##################################################
629 IL    11
Name: patient_state, dtype: int64
##################################################
630 MO    24
Name: patient_state, dtype: int64
##################################################
631 MO    33
Name: patient_state, dtype: int64
##################################################
633 MO    10
Name: patient_state, dtype: int64
##################################################
634 MO    1
Name: patient_state, dtype: int64
##################################################
635 MO    1
Name: patient_state, dtype: int64
##################################################
636 MO    5
Name: patient_state, dtype: int64
##################################################
637 MO    2
Name: patient_state, dtype: int64
##################################################
638 MO    4
Name: patient_state, dtype: int64
##################################################
639 MO    5
Name: patient_state, dtype: int64
##################################################
640 MO    14
Name: patient_state, dtype: int64
##################################################
641 MO    18
Name: patient_state, dtype: int64
##################################################
646 MO    2
Name: patient_state, dtype: int64
##################################################
647 MO    2
Name: patient_state, dtype: int64
##################################################
648 MO    5
Name: patient_state, dtype: int64
##################################################
650 MO    2
Name: patient_state, dtype: int64
##################################################
651 MO    1
Name: patient_state, dtype: int64
##################################################
652 MO    5
Name: patient_state, dtype: int64
##################################################
654 MO    3
Name: patient_state, dtype: int64
##################################################
655 MO    2
Name: patient_state, dtype: int64
##################################################
656 MO    6
Name: patient_state, dtype: int64
##################################################
657 MO    8
Name: patient_state, dtype: int64
##################################################
658 MO    7
Name: patient_state, dtype: int64
##################################################
660 KS    13
Name: patient_state, dtype: int64
##################################################
661 KS    4
Name: patient_state, dtype: int64
##################################################
662 KS    7
Name: patient_state, dtype: int64
##################################################
664 KS    1
Name: patient_state, dtype: int64
##################################################
665 KS    2
Name: patient_state, dtype: int64
##################################################
666 KS    5
Name: patient_state, dtype: int64
##################################################
668 KS    1
Name: patient_state, dtype: int64
##################################################
670 KS    3
Name: patient_state, dtype: int64
##################################################
671 KS    2
Name: patient_state, dtype: int64
##################################################
672 KS    11
Name: patient_state, dtype: int64
##################################################
675 KS    2
Name: patient_state, dtype: int64
##################################################
678 KS    1
Name: patient_state, dtype: int64
##################################################
679 KS    1
Name: patient_state, dtype: int64
##################################################
680 NE    7
Name: patient_state, dtype: int64
##################################################
681 NE    15
Name: patient_state, dtype: int64
##################################################
684 NE    3
Name: patient_state, dtype: int64
##################################################
685 NE    3
Name: patient_state, dtype: int64
##################################################
686 NE    2
Name: patient_state, dtype: int64
##################################################
687 NE    2
Name: patient_state, dtype: int64
##################################################
688 NE    1
Name: patient_state, dtype: int64
##################################################
689 NE    3
Name: patient_state, dtype: int64
##################################################
691 NE    3
Name: patient_state, dtype: int64
##################################################
693 NE    1
Name: patient_state, dtype: int64
##################################################
700 LA    18
Name: patient_state, dtype: int64
##################################################
701 LA    25
Name: patient_state, dtype: int64
##################################################
703 LA    3
Name: patient_state, dtype: int64
##################################################
704 LA    16
Name: patient_state, dtype: int64
##################################################
705 LA    16
Name: patient_state, dtype: int64
##################################################
706 LA    10
Name: patient_state, dtype: int64
##################################################
707 LA    9
Name: patient_state, dtype: int64
##################################################
708 LA    6
Name: patient_state, dtype: int64
##################################################
710 LA    7
Name: patient_state, dtype: int64
##################################################
711 LA    10
Name: patient_state, dtype: int64
##################################################
712 LA    11
Name: patient_state, dtype: int64
##################################################
713 LA    4
Name: patient_state, dtype: int64
##################################################
714 LA    6
Name: patient_state, dtype: int64
##################################################
716 AR    4
Name: patient_state, dtype: int64
##################################################
718 AR    4
Name: patient_state, dtype: int64
##################################################
719 AR    5
Name: patient_state, dtype: int64
##################################################
720 AR    8
Name: patient_state, dtype: int64
##################################################
721 AR    6
Name: patient_state, dtype: int64
##################################################
722 AR    4
Name: patient_state, dtype: int64
##################################################
723 AR    9
Name: patient_state, dtype: int64
##################################################
724 AR    1
Name: patient_state, dtype: int64
##################################################
725 AR    1
Name: patient_state, dtype: int64
##################################################
726 AR    3
Name: patient_state, dtype: int64
##################################################
727 AR    12
Name: patient_state, dtype: int64
##################################################
728 AR    2
Name: patient_state, dtype: int64
##################################################
729 AR    6
Name: patient_state, dtype: int64
##################################################
730 OK    20
Name: patient_state, dtype: int64
##################################################
731 OK    19
Name: patient_state, dtype: int64
##################################################
735 OK    2
Name: patient_state, dtype: int64
##################################################
737 OK    3
Name: patient_state, dtype: int64
##################################################
738 OK    1
Name: patient_state, dtype: int64
##################################################
740 OK    16
Name: patient_state, dtype: int64
##################################################
741 OK    8
Name: patient_state, dtype: int64
##################################################
743 OK    2
Name: patient_state, dtype: int64
##################################################
744 OK    7
Name: patient_state, dtype: int64
##################################################
745 OK    3
Name: patient_state, dtype: int64
##################################################
746 OK    2
Name: patient_state, dtype: int64
##################################################
747 OK    2
Name: patient_state, dtype: int64
##################################################
748 OK    5
Name: patient_state, dtype: int64
##################################################
749 OK    3
Name: patient_state, dtype: int64
##################################################
750 TX    96
Name: patient_state, dtype: int64
##################################################
751 TX    25
Name: patient_state, dtype: int64
##################################################
752 TX    47
Name: patient_state, dtype: int64
##################################################
754 TX    9
Name: patient_state, dtype: int64
##################################################
755 TX    6
Name: patient_state, dtype: int64
##################################################
756 TX    8
Name: patient_state, dtype: int64
##################################################
757 TX    12
Name: patient_state, dtype: int64
##################################################
758 TX    3
Name: patient_state, dtype: int64
##################################################
759 TX    11
Name: patient_state, dtype: int64
##################################################
760 TX    59
Name: patient_state, dtype: int64
##################################################
761 TX    38
Name: patient_state, dtype: int64
##################################################
762 TX    19
Name: patient_state, dtype: int64
##################################################
763 TX    9
Name: patient_state, dtype: int64
##################################################
764 TX    4
Name: patient_state, dtype: int64
##################################################
765 TX    11
Name: patient_state, dtype: int64
##################################################
766 TX    9
Name: patient_state, dtype: int64
##################################################
767 TX    5
Name: patient_state, dtype: int64
##################################################
768 TX    2
Name: patient_state, dtype: int64
##################################################
769 TX    7
Name: patient_state, dtype: int64
##################################################
770 TX    132
Name: patient_state, dtype: int64
##################################################
772 TX    3
Name: patient_state, dtype: int64
##################################################
773 TX    59
Name: patient_state, dtype: int64
##################################################
774 TX    53
Name: patient_state, dtype: int64
##################################################
775 TX    58
Name: patient_state, dtype: int64
##################################################
776 TX    11
Name: patient_state, dtype: int64
##################################################
777 TX    4
Name: patient_state, dtype: int64
##################################################
778 TX    19
Name: patient_state, dtype: int64
##################################################
779 TX    6
Name: patient_state, dtype: int64
##################################################
780 TX    22
Name: patient_state, dtype: int64
##################################################
781 TX    14
Name: patient_state, dtype: int64
##################################################
782 TX    72
Name: patient_state, dtype: int64
##################################################
783 TX    10
Name: patient_state, dtype: int64
##################################################
784 TX    17
Name: patient_state, dtype: int64
##################################################
785 TX    49
Name: patient_state, dtype: int64
##################################################
786 TX    30
Name: patient_state, dtype: int64
##################################################
787 TX    41
Name: patient_state, dtype: int64
##################################################
788 TX    10
Name: patient_state, dtype: int64
##################################################
789 TX    4
Name: patient_state, dtype: int64
##################################################
790 TX    17
Name: patient_state, dtype: int64
##################################################
791 TX    20
Name: patient_state, dtype: int64
##################################################
792 TX    1
Name: patient_state, dtype: int64
##################################################
793 TX    15
Name: patient_state, dtype: int64
##################################################
794 TX    25
Name: patient_state, dtype: int64
##################################################
795 TX    2
Name: patient_state, dtype: int64
##################################################
796 TX    2
Name: patient_state, dtype: int64
##################################################
797 TX    19
Name: patient_state, dtype: int64
##################################################
798 TX    7
Name: patient_state, dtype: int64
##################################################
799 TX    40
Name: patient_state, dtype: int64
##################################################
800 CO    64
Name: patient_state, dtype: int64
##################################################
801 CO    68
Name: patient_state, dtype: int64
##################################################
802 CO    78
Name: patient_state, dtype: int64
##################################################
803 CO    10
Name: patient_state, dtype: int64
##################################################
804 CO    22
Name: patient_state, dtype: int64
##################################################
805 CO    24
Name: patient_state, dtype: int64
##################################################
806 CO    10
Name: patient_state, dtype: int64
##################################################
807 CO    1
Name: patient_state, dtype: int64
##################################################
808 CO    10
Name: patient_state, dtype: int64
##################################################
809 CO    31
Name: patient_state, dtype: int64
##################################################
810 CO    7
Name: patient_state, dtype: int64
##################################################
811 CO    5
Name: patient_state, dtype: int64
##################################################
812 CO    3
Name: patient_state, dtype: int64
##################################################
813 CO    3
Name: patient_state, dtype: int64
##################################################
814 CO    9
Name: patient_state, dtype: int64
##################################################
815 CO    13
Name: patient_state, dtype: int64
##################################################
816 CO    9
Name: patient_state, dtype: int64
##################################################
826 WY    2
Name: patient_state, dtype: int64
##################################################
827 WY    1
Name: patient_state, dtype: int64
##################################################
828 WY    1
Name: patient_state, dtype: int64
##################################################
832 ID    10
Name: patient_state, dtype: int64
##################################################
833 ID    10
Name: patient_state, dtype: int64
##################################################
834 ID    10
Name: patient_state, dtype: int64
##################################################
835 ID    1
Name: patient_state, dtype: int64
##################################################
836 ID    31
Name: patient_state, dtype: int64
##################################################
837 ID    18
Name: patient_state, dtype: int64
##################################################
838 ID    13
Name: patient_state, dtype: int64
##################################################
840 UT    12
Name: patient_state, dtype: int64
##################################################
841 UT    11
Name: patient_state, dtype: int64
##################################################
844 UT    6
Name: patient_state, dtype: int64
##################################################
846 UT    3
Name: patient_state, dtype: int64
##################################################
847 UT    4
Name: patient_state, dtype: int64
##################################################
850 AZ    51
Name: patient_state, dtype: int64
##################################################
851 AZ    10
Name: patient_state, dtype: int64
##################################################
852 AZ    58
Name: patient_state, dtype: int64
##################################################
853 AZ    52
Name: patient_state, dtype: int64
##################################################
855 AZ    2
Name: patient_state, dtype: int64
##################################################
856 AZ    12
Name: patient_state, dtype: int64
##################################################
857 AZ    39
Name: patient_state, dtype: int64
##################################################
859 AZ    2
Name: patient_state, dtype: int64
##################################################
860 AZ    1
Name: patient_state, dtype: int64
##################################################
863 AZ    5
Name: patient_state, dtype: int64
##################################################
864 AZ    1
Name: patient_state, dtype: int64
##################################################
870 NM    18
Name: patient_state, dtype: int64
##################################################
871 NM    58
Name: patient_state, dtype: int64
##################################################
873 NM    3
Name: patient_state, dtype: int64
##################################################
874 NM    5
Name: patient_state, dtype: int64
##################################################
875 NM    24
Name: patient_state, dtype: int64
##################################################
877 NM    6
Name: patient_state, dtype: int64
##################################################
880 NM    13
Name: patient_state, dtype: int64
##################################################
881 NM    1
Name: patient_state, dtype: int64
##################################################
882 NM    11
Name: patient_state, dtype: int64
##################################################
883 NM    6
Name: patient_state, dtype: int64
##################################################
890 NV    12
Name: patient_state, dtype: int64
##################################################
891 NV    30
Name: patient_state, dtype: int64
##################################################
894 NV    10
Name: patient_state, dtype: int64
##################################################
895 NV    7
Name: patient_state, dtype: int64
##################################################
897 NV    1
Name: patient_state, dtype: int64
##################################################
900 CA    239
Name: patient_state, dtype: int64
##################################################
902 CA    116
Name: patient_state, dtype: int64
##################################################
903 CA    5
Name: patient_state, dtype: int64
##################################################
904 CA    5
Name: patient_state, dtype: int64
##################################################
905 CA    16
Name: patient_state, dtype: int64
##################################################
906 CA    73
Name: patient_state, dtype: int64
##################################################
907 CA    63
Name: patient_state, dtype: int64
##################################################
908 CA    36
Name: patient_state, dtype: int64
##################################################
910 CA    32
Name: patient_state, dtype: int64
##################################################
911 CA    21
Name: patient_state, dtype: int64
##################################################
912 CA    30
Name: patient_state, dtype: int64
##################################################
913 CA    127
Name: patient_state, dtype: int64
##################################################
914 CA    23
Name: patient_state, dtype: int64
##################################################
915 CA    10
Name: patient_state, dtype: int64
##################################################
916 CA    18
Name: patient_state, dtype: int64
##################################################
917 CA    170
Name: patient_state, dtype: int64
##################################################
918 CA    11
Name: patient_state, dtype: int64
##################################################
919 CA    25
Name: patient_state, dtype: int64
##################################################
920 CA    79
Name: patient_state, dtype: int64
##################################################
921 CA    49
Name: patient_state, dtype: int64
##################################################
922 CA    49
Name: patient_state, dtype: int64
##################################################
923 CA    103
Name: patient_state, dtype: int64
##################################################
924 CA    18
Name: patient_state, dtype: int64
##################################################
925 CA    86
Name: patient_state, dtype: int64
##################################################
926 CA    118
Name: patient_state, dtype: int64
##################################################
927 CA    33
Name: patient_state, dtype: int64
##################################################
928 CA    96
Name: patient_state, dtype: int64
##################################################
930 CA    35
Name: patient_state, dtype: int64
##################################################
931 CA    13
Name: patient_state, dtype: int64
##################################################
932 CA    38
Name: patient_state, dtype: int64
##################################################
933 CA    24
Name: patient_state, dtype: int64
##################################################
934 CA    31
Name: patient_state, dtype: int64
##################################################
935 CA    36
Name: patient_state, dtype: int64
##################################################
936 CA    36
Name: patient_state, dtype: int64
##################################################
937 CA    23
Name: patient_state, dtype: int64
##################################################
939 CA    27
Name: patient_state, dtype: int64
##################################################
940 CA    34
Name: patient_state, dtype: int64
##################################################
941 CA    37
Name: patient_state, dtype: int64
##################################################
943 CA    4
Name: patient_state, dtype: int64
##################################################
944 CA    3
Name: patient_state, dtype: int64
##################################################
945 CA    68
Name: patient_state, dtype: int64
##################################################
946 CA    21
Name: patient_state, dtype: int64
##################################################
947 CA    9
Name: patient_state, dtype: int64
##################################################
948 CA    6
Name: patient_state, dtype: int64
##################################################
949 CA    21
Name: patient_state, dtype: int64
##################################################
950 CA    50
Name: patient_state, dtype: int64
##################################################
951 CA    29
Name: patient_state, dtype: int64
##################################################
952 CA    23
Name: patient_state, dtype: int64
##################################################
953 CA    50
Name: patient_state, dtype: int64
##################################################
954 CA    18
Name: patient_state, dtype: int64
##################################################
955 CA    13
Name: patient_state, dtype: int64
##################################################
956 CA    55
Name: patient_state, dtype: int64
##################################################
957 CA    11
Name: patient_state, dtype: int64
##################################################
958 CA    35
Name: patient_state, dtype: int64
##################################################
959 CA    41
Name: patient_state, dtype: int64
##################################################
960 CA    16
Name: patient_state, dtype: int64
##################################################
961 CA    5
Name: patient_state, dtype: int64
##################################################
967 HI    12
Name: patient_state, dtype: int64
##################################################
968 HI    11
Name: patient_state, dtype: int64
##################################################
970 OR    14
Name: patient_state, dtype: int64
##################################################
971 OR    9
Name: patient_state, dtype: int64
##################################################
972 OR    16
Name: patient_state, dtype: int64
##################################################
973 OR    13
Name: patient_state, dtype: int64
##################################################
974 OR    20
Name: patient_state, dtype: int64
##################################################
975 OR    13
Name: patient_state, dtype: int64
##################################################
976 OR    2
Name: patient_state, dtype: int64
##################################################
977 OR    1
Name: patient_state, dtype: int64
##################################################
978 OR    2
Name: patient_state, dtype: int64
##################################################
980 WA    48
Name: patient_state, dtype: int64
##################################################
981 WA    27
Name: patient_state, dtype: int64
##################################################
982 WA    27
Name: patient_state, dtype: int64
##################################################
983 WA    19
Name: patient_state, dtype: int64
##################################################
984 WA    15
Name: patient_state, dtype: int64
##################################################
985 WA    5
Name: patient_state, dtype: int64
##################################################
986 WA    12
Name: patient_state, dtype: int64
##################################################
988 WA    10
Name: patient_state, dtype: int64
##################################################
989 WA    3
Name: patient_state, dtype: int64
##################################################
990 WA    7
Name: patient_state, dtype: int64
##################################################
991 WA    9
Name: patient_state, dtype: int64
##################################################
992 WA    12
Name: patient_state, dtype: int64
##################################################
993 WA    6
Name: patient_state, dtype: int64
##################################################
994 WA    1
Name: patient_state, dtype: int64
##################################################
995 AK    2
Name: patient_state, dtype: int64
##################################################
996 AK    2
Name: patient_state, dtype: int64
##################################################
998 AK    1
Name: patient_state, dtype: int64
##################################################
999 AK    1
Name: patient_state, dtype: int64
In [39]:
stocker_Region  = dict()
for zp in patient_zip3 : 
    stocker_Region[zp] = train[train['patient_zip3'] == zp].Region.value_counts().sort_values().index[-1]
    print("#"*50)
    print(zp , train[train['patient_zip3'] == zp].Region.value_counts().sort_values())

    
for i in train.index:
    train.at[i, "Region"] = stocker_Region.get(train.at[i, "patient_zip3"], None)
##################################################
101 Northeast    2
Name: Region, dtype: int64
##################################################
103 South         1
Northeast    34
Name: Region, dtype: int64
##################################################
104 South          2
Northeast    110
Name: Region, dtype: int64
##################################################
105 Northeast    33
Name: Region, dtype: int64
##################################################
106 Northeast    5
Name: Region, dtype: int64
##################################################
107 Northeast    11
Name: Region, dtype: int64
##################################################
108 Northeast    7
Name: Region, dtype: int64
##################################################
109 South         1
Northeast    16
Name: Region, dtype: int64
##################################################
110 Northeast    15
Name: Region, dtype: int64
##################################################
111 Northeast    13
Name: Region, dtype: int64
##################################################
112 West           1
South          1
Northeast    190
Name: Region, dtype: int64
##################################################
113 West          1
South         2
Northeast    68
Name: Region, dtype: int64
##################################################
114 South         2
Northeast    55
Name: Region, dtype: int64
##################################################
115 Northeast    40
Name: Region, dtype: int64
##################################################
116 Northeast    8
Name: Region, dtype: int64
##################################################
117 South         4
Northeast    67
Name: Region, dtype: int64
##################################################
118 Northeast    1
West         1
Name: Region, dtype: int64
##################################################
119 South         1
Northeast    13
Name: Region, dtype: int64
##################################################
120 Northeast    27
Name: Region, dtype: int64
##################################################
121 Northeast    25
Name: Region, dtype: int64
##################################################
122 West          1
Northeast    13
Name: Region, dtype: int64
##################################################
123 Northeast    14
Name: Region, dtype: int64
##################################################
124 Northeast    11
Name: Region, dtype: int64
##################################################
125 Northeast    23
Name: Region, dtype: int64
##################################################
126 Northeast    3
Name: Region, dtype: int64
##################################################
127 South        1
Northeast    7
Name: Region, dtype: int64
##################################################
128 Northeast    19
Name: Region, dtype: int64
##################################################
129 Northeast    4
Name: Region, dtype: int64
##################################################
130 Northeast    5
Name: Region, dtype: int64
##################################################
131 Northeast    2
Name: Region, dtype: int64
##################################################
132 Northeast    6
Name: Region, dtype: int64
##################################################
133 Northeast    3
Name: Region, dtype: int64
##################################################
134 Northeast    7
Name: Region, dtype: int64
##################################################
135 Northeast    2
Name: Region, dtype: int64
##################################################
136 Northeast    9
Name: Region, dtype: int64
##################################################
137 Northeast    4
Name: Region, dtype: int64
##################################################
138 Northeast    7
Name: Region, dtype: int64
##################################################
139 Northeast    1
Name: Region, dtype: int64
##################################################
140 Northeast    39
Name: Region, dtype: int64
##################################################
141 Northeast    25
Name: Region, dtype: int64
##################################################
142 Northeast    50
Name: Region, dtype: int64
##################################################
143 Northeast    6
Name: Region, dtype: int64
##################################################
144 Northeast    9
Name: Region, dtype: int64
##################################################
145 Northeast    11
Name: Region, dtype: int64
##################################################
146 Northeast    23
Name: Region, dtype: int64
##################################################
147 Northeast    8
Name: Region, dtype: int64
##################################################
148 Northeast    5
Name: Region, dtype: int64
##################################################
149 Northeast    1
Name: Region, dtype: int64
##################################################
150 Northeast    6
Name: Region, dtype: int64
##################################################
151 Northeast    11
Name: Region, dtype: int64
##################################################
152 Northeast    11
Name: Region, dtype: int64
##################################################
154 Northeast    2
Name: Region, dtype: int64
##################################################
155 Northeast    1
Name: Region, dtype: int64
##################################################
156 Northeast    9
Name: Region, dtype: int64
##################################################
157 Northeast    1
Name: Region, dtype: int64
##################################################
158 Northeast    2
Name: Region, dtype: int64
##################################################
159 Northeast    2
Name: Region, dtype: int64
##################################################
160 Northeast    5
Name: Region, dtype: int64
##################################################
161 Northeast    2
Name: Region, dtype: int64
##################################################
162 Northeast    1
Name: Region, dtype: int64
##################################################
163 Northeast    1
Name: Region, dtype: int64
##################################################
164 Northeast    4
Name: Region, dtype: int64
##################################################
165 Northeast    7
Name: Region, dtype: int64
##################################################
166 Northeast    3
Name: Region, dtype: int64
##################################################
168 Northeast    2
Name: Region, dtype: int64
##################################################
169 Northeast    2
Name: Region, dtype: int64
##################################################
170 Midwest       1
Northeast    20
Name: Region, dtype: int64
##################################################
171 South        1
Northeast    6
Name: Region, dtype: int64
##################################################
172 Northeast    4
Name: Region, dtype: int64
##################################################
173 Northeast    10
Name: Region, dtype: int64
##################################################
174 Northeast    4
Name: Region, dtype: int64
##################################################
175 Northeast    9
Name: Region, dtype: int64
##################################################
176 Northeast    6
Name: Region, dtype: int64
##################################################
177 Northeast    7
Name: Region, dtype: int64
##################################################
178 Northeast    13
Name: Region, dtype: int64
##################################################
179 Northeast    6
Name: Region, dtype: int64
##################################################
180 Northeast    24
Name: Region, dtype: int64
##################################################
181 Northeast    9
Name: Region, dtype: int64
##################################################
182 Northeast    5
Name: Region, dtype: int64
##################################################
183 Northeast    15
Name: Region, dtype: int64
##################################################
184 Northeast    6
Name: Region, dtype: int64
##################################################
185 Northeast    5
Name: Region, dtype: int64
##################################################
186 Northeast    11
Name: Region, dtype: int64
##################################################
187 Northeast    3
Name: Region, dtype: int64
##################################################
189 Northeast    32
Name: Region, dtype: int64
##################################################
190 South         2
Northeast    62
Name: Region, dtype: int64
##################################################
191 South         3
Northeast    88
Name: Region, dtype: int64
##################################################
193 West          1
Northeast    17
Name: Region, dtype: int64
##################################################
194 Northeast    37
Name: Region, dtype: int64
##################################################
195 Northeast    3
Name: Region, dtype: int64
##################################################
196 South        1
Northeast    5
Name: Region, dtype: int64
##################################################
197 South    7
Name: Region, dtype: int64
##################################################
198 South    6
Name: Region, dtype: int64
##################################################
199 South    16
Name: Region, dtype: int64
##################################################
200 South    20
Name: Region, dtype: int64
##################################################
201 South    23
Name: Region, dtype: int64
##################################################
206 South    4
Name: Region, dtype: int64
##################################################
207 South    11
Name: Region, dtype: int64
##################################################
208 Northeast     1
South        11
Name: Region, dtype: int64
##################################################
209 South    4
Name: Region, dtype: int64
##################################################
210 South    7
Name: Region, dtype: int64
##################################################
211 South    8
Name: Region, dtype: int64
##################################################
212 South    14
Name: Region, dtype: int64
##################################################
215 South    3
Name: Region, dtype: int64
##################################################
216 South    2
Name: Region, dtype: int64
##################################################
217 South    8
Name: Region, dtype: int64
##################################################
220 South    11
Name: Region, dtype: int64
##################################################
221 South    15
Name: Region, dtype: int64
##################################################
222 South    5
Name: Region, dtype: int64
##################################################
223 South    6
Name: Region, dtype: int64
##################################################
224 South    8
Name: Region, dtype: int64
##################################################
225 South    6
Name: Region, dtype: int64
##################################################
226 South    7
Name: Region, dtype: int64
##################################################
227 South    6
Name: Region, dtype: int64
##################################################
228 South    10
Name: Region, dtype: int64
##################################################
229 South    16
Name: Region, dtype: int64
##################################################
230 South    16
Name: Region, dtype: int64
##################################################
231 South    17
Name: Region, dtype: int64
##################################################
232 South    28
Name: Region, dtype: int64
##################################################
233 West      1
South    19
Name: Region, dtype: int64
##################################################
234 South    30
Name: Region, dtype: int64
##################################################
235 Midwest       1
Northeast     1
South        12
Name: Region, dtype: int64
##################################################
236 South    21
Name: Region, dtype: int64
##################################################
237 South    3
Name: Region, dtype: int64
##################################################
238 South    25
Name: Region, dtype: int64
##################################################
239 South    9
Name: Region, dtype: int64
##################################################
240 South    17
Name: Region, dtype: int64
##################################################
241 South    11
Name: Region, dtype: int64
##################################################
242 South    7
Name: Region, dtype: int64
##################################################
243 South    6
Name: Region, dtype: int64
##################################################
244 South    7
Name: Region, dtype: int64
##################################################
245 South    18
Name: Region, dtype: int64
##################################################
246 South    5
Name: Region, dtype: int64
##################################################
247 South    1
Name: Region, dtype: int64
##################################################
248 South    3
Name: Region, dtype: int64
##################################################
251 South    1
Name: Region, dtype: int64
##################################################
252 South    1
Name: Region, dtype: int64
##################################################
253 South    2
Name: Region, dtype: int64
##################################################
254 South    2
Name: Region, dtype: int64
##################################################
255 South    1
Name: Region, dtype: int64
##################################################
256 South    1
Name: Region, dtype: int64
##################################################
259 South    2
Name: Region, dtype: int64
##################################################
260 South    3
Name: Region, dtype: int64
##################################################
261 South    1
Name: Region, dtype: int64
##################################################
262 South    3
Name: Region, dtype: int64
##################################################
263 South    1
Name: Region, dtype: int64
##################################################
264 South    1
Name: Region, dtype: int64
##################################################
265 South    1
Name: Region, dtype: int64
##################################################
267 South    3
Name: Region, dtype: int64
##################################################
270 South    7
Name: Region, dtype: int64
##################################################
271 South    9
Name: Region, dtype: int64
##################################################
272 South    12
Name: Region, dtype: int64
##################################################
273 South    4
Name: Region, dtype: int64
##################################################
274 South    5
Name: Region, dtype: int64
##################################################
275 Northeast     1
South        22
Name: Region, dtype: int64
##################################################
276 South    9
Name: Region, dtype: int64
##################################################
277 South    4
Name: Region, dtype: int64
##################################################
278 South    11
Name: Region, dtype: int64
##################################################
279 South    5
Name: Region, dtype: int64
##################################################
280 South    16
Name: Region, dtype: int64
##################################################
281 South    7
Name: Region, dtype: int64
##################################################
282 South    20
Name: Region, dtype: int64
##################################################
283 South    14
Name: Region, dtype: int64
##################################################
284 South    9
Name: Region, dtype: int64
##################################################
285 South    6
Name: Region, dtype: int64
##################################################
286 South    8
Name: Region, dtype: int64
##################################################
287 South    11
Name: Region, dtype: int64
##################################################
288 South    2
Name: Region, dtype: int64
##################################################
290 South    12
Name: Region, dtype: int64
##################################################
291 South    10
Name: Region, dtype: int64
##################################################
292 South    8
Name: Region, dtype: int64
##################################################
293 South    7
Name: Region, dtype: int64
##################################################
294 South    14
Name: Region, dtype: int64
##################################################
295 South    11
Name: Region, dtype: int64
##################################################
296 South    21
Name: Region, dtype: int64
##################################################
297 South    13
Name: Region, dtype: int64
##################################################
298 South    7
Name: Region, dtype: int64
##################################################
299 South    6
Name: Region, dtype: int64
##################################################
300 South    120
Name: Region, dtype: int64
##################################################
301 South    59
Name: Region, dtype: int64
##################################################
302 South    53
Name: Region, dtype: int64
##################################################
303 South    48
Name: Region, dtype: int64
##################################################
304 South    13
Name: Region, dtype: int64
##################################################
305 South    33
Name: Region, dtype: int64
##################################################
306 South    25
Name: Region, dtype: int64
##################################################
307 South    15
Name: Region, dtype: int64
##################################################
308 South    7
Name: Region, dtype: int64
##################################################
309 South    13
Name: Region, dtype: int64
##################################################
310 South    28
Name: Region, dtype: int64
##################################################
312 South    6
Name: Region, dtype: int64
##################################################
313 South    10
Name: Region, dtype: int64
##################################################
314 South    22
Name: Region, dtype: int64
##################################################
315 South    27
Name: Region, dtype: int64
##################################################
316 South    14
Name: Region, dtype: int64
##################################################
317 South    35
Name: Region, dtype: int64
##################################################
318 South    5
Name: Region, dtype: int64
##################################################
319 South    9
Name: Region, dtype: int64
##################################################
320 Northeast     1
South        11
Name: Region, dtype: int64
##################################################
321 West      1
South    14
Name: Region, dtype: int64
##################################################
322 South    28
Name: Region, dtype: int64
##################################################
323 South    7
Name: Region, dtype: int64
##################################################
324 South    11
Name: Region, dtype: int64
##################################################
325 South    9
Name: Region, dtype: int64
##################################################
326 South    3
Name: Region, dtype: int64
##################################################
327 Midwest     2
South      17
Name: Region, dtype: int64
##################################################
328 South    30
Name: Region, dtype: int64
##################################################
329 South    15
Name: Region, dtype: int64
##################################################
330 South    66
Name: Region, dtype: int64
##################################################
331 South    91
Name: Region, dtype: int64
##################################################
332 South    1
Name: Region, dtype: int64
##################################################
333 South    20
Name: Region, dtype: int64
##################################################
334 Northeast     1
South        33
Name: Region, dtype: int64
##################################################
335 South    22
Name: Region, dtype: int64
##################################################
336 South    34
Name: Region, dtype: int64
##################################################
337 South    30
Name: Region, dtype: int64
##################################################
338 South    26
Name: Region, dtype: int64
##################################################
339 South    23
Name: Region, dtype: int64
##################################################
341 South    5
Name: Region, dtype: int64
##################################################
342 South    33
Name: Region, dtype: int64
##################################################
344 South    6
Name: Region, dtype: int64
##################################################
346 South    26
Name: Region, dtype: int64
##################################################
347 Midwest       1
Northeast     1
South        17
Name: Region, dtype: int64
##################################################
349 South    15
Name: Region, dtype: int64
##################################################
350 South    5
Name: Region, dtype: int64
##################################################
351 South    1
Name: Region, dtype: int64
##################################################
352 South    4
Name: Region, dtype: int64
##################################################
354 South    2
Name: Region, dtype: int64
##################################################
356 South    7
Name: Region, dtype: int64
##################################################
357 South    5
Name: Region, dtype: int64
##################################################
358 South    3
Name: Region, dtype: int64
##################################################
359 South    4
Name: Region, dtype: int64
##################################################
360 South    2
Name: Region, dtype: int64
##################################################
361 South    1
Name: Region, dtype: int64
##################################################
363 South    2
Name: Region, dtype: int64
##################################################
365 South    6
Name: Region, dtype: int64
##################################################
366 South    2
Name: Region, dtype: int64
##################################################
367 South    1
Name: Region, dtype: int64
##################################################
368 South    7
Name: Region, dtype: int64
##################################################
370 Midwest     1
South      15
Name: Region, dtype: int64
##################################################
371 South    14
Name: Region, dtype: int64
##################################################
372 South    3
Name: Region, dtype: int64
##################################################
373 South    4
Name: Region, dtype: int64
##################################################
374 South    3
Name: Region, dtype: int64
##################################################
376 South    4
Name: Region, dtype: int64
##################################################
377 South    7
Name: Region, dtype: int64
##################################################
378 South    10
Name: Region, dtype: int64
##################################################
379 South    4
Name: Region, dtype: int64
##################################################
380 South    7
Name: Region, dtype: int64
##################################################
381 South    21
Name: Region, dtype: int64
##################################################
382 South    3
Name: Region, dtype: int64
##################################################
383 South    6
Name: Region, dtype: int64
##################################################
384 South    6
Name: Region, dtype: int64
##################################################
385 South    5
Name: Region, dtype: int64
##################################################
386 South    9
Name: Region, dtype: int64
##################################################
387 South    4
Name: Region, dtype: int64
##################################################
388 South    3
Name: Region, dtype: int64
##################################################
389 South    3
Name: Region, dtype: int64
##################################################
390 South    11
Name: Region, dtype: int64
##################################################
391 South    12
Name: Region, dtype: int64
##################################################
392 South    12
Name: Region, dtype: int64
##################################################
393 South    2
Name: Region, dtype: int64
##################################################
394 South    6
Name: Region, dtype: int64
##################################################
395 South    8
Name: Region, dtype: int64
##################################################
396 South    3
Name: Region, dtype: int64
##################################################
397 South    1
Name: Region, dtype: int64
##################################################
398 South    8
Name: Region, dtype: int64
##################################################
400 South    20
Name: Region, dtype: int64
##################################################
401 South    8
Name: Region, dtype: int64
##################################################
402 Midwest     1
South      44
Name: Region, dtype: int64
##################################################
403 South    14
Name: Region, dtype: int64
##################################################
404 South    15
Name: Region, dtype: int64
##################################################
405 South    30
Name: Region, dtype: int64
##################################################
406 South    3
Name: Region, dtype: int64
##################################################
407 South    7
Name: Region, dtype: int64
##################################################
408 South    2
Name: Region, dtype: int64
##################################################
409 South    4
Name: Region, dtype: int64
##################################################
410 South    23
Name: Region, dtype: int64
##################################################
411 South    8
Name: Region, dtype: int64
##################################################
412 South    2
Name: Region, dtype: int64
##################################################
413 South    2
Name: Region, dtype: int64
##################################################
414 South    2
Name: Region, dtype: int64
##################################################
415 South    3
Name: Region, dtype: int64
##################################################
416 South    1
Name: Region, dtype: int64
##################################################
417 South    3
Name: Region, dtype: int64
##################################################
418 South    3
Name: Region, dtype: int64
##################################################
420 South    6
Name: Region, dtype: int64
##################################################
421 South    13
Name: Region, dtype: int64
##################################################
422 South    6
Name: Region, dtype: int64
##################################################
423 South    13
Name: Region, dtype: int64
##################################################
424 South    4
Name: Region, dtype: int64
##################################################
425 South    3
Name: Region, dtype: int64
##################################################
426 South    5
Name: Region, dtype: int64
##################################################
427 South    11
Name: Region, dtype: int64
##################################################
430 Midwest    60
Name: Region, dtype: int64
##################################################
431 Midwest    26
Name: Region, dtype: int64
##################################################
432 Midwest    52
Name: Region, dtype: int64
##################################################
433 Midwest    9
Name: Region, dtype: int64
##################################################
434 Midwest    12
Name: Region, dtype: int64
##################################################
435 West        1
Midwest    17
Name: Region, dtype: int64
##################################################
436 Midwest    22
Name: Region, dtype: int64
##################################################
437 Midwest    13
Name: Region, dtype: int64
##################################################
438 Midwest    4
Name: Region, dtype: int64
##################################################
439 Midwest    7
Name: Region, dtype: int64
##################################################
440 Midwest    72
Name: Region, dtype: int64
##################################################
441 Midwest    74
Name: Region, dtype: int64
##################################################
442 South       1
Midwest    43
Name: Region, dtype: int64
##################################################
443 Midwest    26
Name: Region, dtype: int64
##################################################
444 Midwest    13
Name: Region, dtype: int64
##################################################
445 Northeast     1
Midwest      20
Name: Region, dtype: int64
##################################################
446 Midwest    28
Name: Region, dtype: int64
##################################################
447 Midwest    15
Name: Region, dtype: int64
##################################################
448 Midwest    25
Name: Region, dtype: int64
##################################################
449 Midwest    8
Name: Region, dtype: int64
##################################################
450 South       1
Midwest    26
Name: Region, dtype: int64
##################################################
451 Midwest    14
Name: Region, dtype: int64
##################################################
452 Midwest    35
Name: Region, dtype: int64
##################################################
453 Midwest    42
Name: Region, dtype: int64
##################################################
454 Midwest    35
Name: Region, dtype: int64
##################################################
455 Midwest    5
Name: Region, dtype: int64
##################################################
456 Midwest    14
Name: Region, dtype: int64
##################################################
457 Midwest    12
Name: Region, dtype: int64
##################################################
458 Midwest    20
Name: Region, dtype: int64
##################################################
460 Midwest    32
Name: Region, dtype: int64
##################################################
461 Midwest    29
Name: Region, dtype: int64
##################################################
462 Midwest    59
Name: Region, dtype: int64
##################################################
463 Midwest    34
Name: Region, dtype: int64
##################################################
464 Midwest    7
Name: Region, dtype: int64
##################################################
465 Midwest    24
Name: Region, dtype: int64
##################################################
466 Midwest    6
Name: Region, dtype: int64
##################################################
467 Midwest    13
Name: Region, dtype: int64
##################################################
468 Midwest    13
Name: Region, dtype: int64
##################################################
469 Midwest    15
Name: Region, dtype: int64
##################################################
470 Midwest    8
Name: Region, dtype: int64
##################################################
471 South       1
Midwest    17
Name: Region, dtype: int64
##################################################
472 Midwest    13
Name: Region, dtype: int64
##################################################
473 South       1
Midwest    10
Name: Region, dtype: int64
##################################################
474 Midwest    11
Name: Region, dtype: int64
##################################################
475 Midwest    5
Name: Region, dtype: int64
##################################################
476 Midwest    2
Name: Region, dtype: int64
##################################################
477 South      1
Midwest    2
Name: Region, dtype: int64
##################################################
478 Midwest    6
Name: Region, dtype: int64
##################################################
479 Midwest    10
Name: Region, dtype: int64
##################################################
480 Midwest    103
Name: Region, dtype: int64
##################################################
481 Midwest    131
Name: Region, dtype: int64
##################################################
482 West        2
Midwest    96
Name: Region, dtype: int64
##################################################
483 Midwest    95
Name: Region, dtype: int64
##################################################
484 Midwest    37
Name: Region, dtype: int64
##################################################
485 South       1
Midwest    18
Name: Region, dtype: int64
##################################################
486 Midwest    28
Name: Region, dtype: int64
##################################################
487 Midwest    11
Name: Region, dtype: int64
##################################################
488 South       1
Midwest    48
Name: Region, dtype: int64
##################################################
489 Midwest    10
Name: Region, dtype: int64
##################################################
490 Midwest    57
Name: Region, dtype: int64
##################################################
491 West       1
Midwest    7
Name: Region, dtype: int64
##################################################
492 Midwest    37
Name: Region, dtype: int64
##################################################
493 Midwest    34
Name: Region, dtype: int64
##################################################
494 Midwest    44
Name: Region, dtype: int64
##################################################
495 Midwest    36
Name: Region, dtype: int64
##################################################
496 Midwest    21
Name: Region, dtype: int64
##################################################
497 Midwest    18
Name: Region, dtype: int64
##################################################
498 Midwest    19
Name: Region, dtype: int64
##################################################
499 Midwest    7
Name: Region, dtype: int64
##################################################
500 Midwest    4
Name: Region, dtype: int64
##################################################
501 Midwest    4
Name: Region, dtype: int64
##################################################
502 Midwest    3
Name: Region, dtype: int64
##################################################
503 Midwest    7
Name: Region, dtype: int64
##################################################
504 Midwest    8
Name: Region, dtype: int64
##################################################
505 Midwest    6
Name: Region, dtype: int64
##################################################
506 Midwest    1
Name: Region, dtype: int64
##################################################
507 Midwest    4
Name: Region, dtype: int64
##################################################
510 Midwest    2
Name: Region, dtype: int64
##################################################
511 Midwest    5
Name: Region, dtype: int64
##################################################
512 Midwest    1
Name: Region, dtype: int64
##################################################
514 Midwest    1
Name: Region, dtype: int64
##################################################
515 Midwest    3
Name: Region, dtype: int64
##################################################
516 Midwest    2
Name: Region, dtype: int64
##################################################
520 Midwest    5
Name: Region, dtype: int64
##################################################
522 Midwest    7
Name: Region, dtype: int64
##################################################
523 Midwest    4
Name: Region, dtype: int64
##################################################
524 Midwest    5
Name: Region, dtype: int64
##################################################
525 Midwest    5
Name: Region, dtype: int64
##################################################
526 Midwest    1
Name: Region, dtype: int64
##################################################
527 Midwest    4
Name: Region, dtype: int64
##################################################
528 Midwest    4
Name: Region, dtype: int64
##################################################
530 Midwest    19
Name: Region, dtype: int64
##################################################
531 Midwest    37
Name: Region, dtype: int64
##################################################
532 South       1
Midwest    20
Name: Region, dtype: int64
##################################################
534 Midwest    2
Name: Region, dtype: int64
##################################################
535 Midwest    24
Name: Region, dtype: int64
##################################################
537 Midwest    8
Name: Region, dtype: int64
##################################################
539 Midwest    5
Name: Region, dtype: int64
##################################################
540 Midwest    2
Name: Region, dtype: int64
##################################################
541 Midwest    13
Name: Region, dtype: int64
##################################################
542 Midwest    15
Name: Region, dtype: int64
##################################################
543 Midwest    7
Name: Region, dtype: int64
##################################################
544 Midwest    5
Name: Region, dtype: int64
##################################################
545 Midwest    3
Name: Region, dtype: int64
##################################################
546 Midwest    4
Name: Region, dtype: int64
##################################################
547 Midwest    7
Name: Region, dtype: int64
##################################################
548 Midwest    5
Name: Region, dtype: int64
##################################################
549 Midwest    32
Name: Region, dtype: int64
##################################################
550 Midwest    47
Name: Region, dtype: int64
##################################################
551 Midwest    39
Name: Region, dtype: int64
##################################################
553 Midwest    63
Name: Region, dtype: int64
##################################################
554 Midwest    47
Name: Region, dtype: int64
##################################################
557 Midwest    13
Name: Region, dtype: int64
##################################################
558 Midwest    7
Name: Region, dtype: int64
##################################################
559 Midwest    26
Name: Region, dtype: int64
##################################################
560 Midwest    37
Name: Region, dtype: int64
##################################################
561 Midwest    7
Name: Region, dtype: int64
##################################################
562 Midwest    19
Name: Region, dtype: int64
##################################################
563 Midwest    24
Name: Region, dtype: int64
##################################################
564 Midwest    10
Name: Region, dtype: int64
##################################################
565 Midwest    23
Name: Region, dtype: int64
##################################################
566 Midwest    6
Name: Region, dtype: int64
##################################################
567 Midwest    7
Name: Region, dtype: int64
##################################################
570 Midwest    2
Name: Region, dtype: int64
##################################################
573 Midwest    1
Name: Region, dtype: int64
##################################################
574 Midwest    1
Name: Region, dtype: int64
##################################################
577 Midwest    4
Name: Region, dtype: int64
##################################################
581 Midwest    3
Name: Region, dtype: int64
##################################################
582 Midwest    1
Name: Region, dtype: int64
##################################################
585 Midwest    1
Name: Region, dtype: int64
##################################################
587 Midwest    1
Name: Region, dtype: int64
##################################################
590 West    2
Name: Region, dtype: int64
##################################################
591 West    10
Name: Region, dtype: int64
##################################################
592 West    1
Name: Region, dtype: int64
##################################################
593 West    2
Name: Region, dtype: int64
##################################################
594 West    6
Name: Region, dtype: int64
##################################################
596 West    3
Name: Region, dtype: int64
##################################################
597 West    6
Name: Region, dtype: int64
##################################################
598 West    5
Name: Region, dtype: int64
##################################################
599 West    9
Name: Region, dtype: int64
##################################################
600 Midwest    104
Name: Region, dtype: int64
##################################################
601 Northeast     1
Midwest      91
Name: Region, dtype: int64
##################################################
602 Midwest    9
Name: Region, dtype: int64
##################################################
603 Midwest    7
Name: Region, dtype: int64
##################################################
604 Midwest    96
Name: Region, dtype: int64
##################################################
605 South       1
Midwest    99
Name: Region, dtype: int64
##################################################
606 Midwest    150
Name: Region, dtype: int64
##################################################
607 Midwest    7
Name: Region, dtype: int64
##################################################
608 Midwest    2
Name: Region, dtype: int64
##################################################
609 Midwest    13
Name: Region, dtype: int64
##################################################
610 Midwest    15
Name: Region, dtype: int64
##################################################
611 Midwest    10
Name: Region, dtype: int64
##################################################
612 Midwest    11
Name: Region, dtype: int64
##################################################
613 Midwest    9
Name: Region, dtype: int64
##################################################
614 Midwest    6
Name: Region, dtype: int64
##################################################
615 Midwest    14
Name: Region, dtype: int64
##################################################
616 Midwest    9
Name: Region, dtype: int64
##################################################
617 Midwest    18
Name: Region, dtype: int64
##################################################
618 Midwest    11
Name: Region, dtype: int64
##################################################
619 Midwest    7
Name: Region, dtype: int64
##################################################
620 Midwest    7
Name: Region, dtype: int64
##################################################
622 Midwest    18
Name: Region, dtype: int64
##################################################
623 Midwest    2
Name: Region, dtype: int64
##################################################
624 Midwest    6
Name: Region, dtype: int64
##################################################
625 Midwest    14
Name: Region, dtype: int64
##################################################
626 Midwest    16
Name: Region, dtype: int64
##################################################
627 Midwest    11
Name: Region, dtype: int64
##################################################
628 Midwest    10
Name: Region, dtype: int64
##################################################
629 Midwest    11
Name: Region, dtype: int64
##################################################
630 Midwest    24
Name: Region, dtype: int64
##################################################
631 Midwest    33
Name: Region, dtype: int64
##################################################
633 Midwest    10
Name: Region, dtype: int64
##################################################
634 Midwest    1
Name: Region, dtype: int64
##################################################
635 Midwest    1
Name: Region, dtype: int64
##################################################
636 Midwest    5
Name: Region, dtype: int64
##################################################
637 Midwest    2
Name: Region, dtype: int64
##################################################
638 Midwest    4
Name: Region, dtype: int64
##################################################
639 Midwest    5
Name: Region, dtype: int64
##################################################
640 Midwest    14
Name: Region, dtype: int64
##################################################
641 Midwest    18
Name: Region, dtype: int64
##################################################
646 Midwest    2
Name: Region, dtype: int64
##################################################
647 Midwest    2
Name: Region, dtype: int64
##################################################
648 Midwest    5
Name: Region, dtype: int64
##################################################
650 Midwest    2
Name: Region, dtype: int64
##################################################
651 Midwest    1
Name: Region, dtype: int64
##################################################
652 Midwest    5
Name: Region, dtype: int64
##################################################
654 Midwest    3
Name: Region, dtype: int64
##################################################
655 Midwest    2
Name: Region, dtype: int64
##################################################
656 Midwest    6
Name: Region, dtype: int64
##################################################
657 Midwest    8
Name: Region, dtype: int64
##################################################
658 Midwest    7
Name: Region, dtype: int64
##################################################
660 Midwest    12
Name: Region, dtype: int64
##################################################
661 Midwest    4
Name: Region, dtype: int64
##################################################
662 Midwest    6
Name: Region, dtype: int64
##################################################
664 Midwest    1
Name: Region, dtype: int64
##################################################
665 Midwest    2
Name: Region, dtype: int64
##################################################
666 Midwest    4
Name: Region, dtype: int64
##################################################
668 Midwest    1
Name: Region, dtype: int64
##################################################
670 Midwest    3
Name: Region, dtype: int64
##################################################
671 Midwest    2
Name: Region, dtype: int64
##################################################
672 Midwest    11
Name: Region, dtype: int64
##################################################
675 Midwest    2
Name: Region, dtype: int64
##################################################
678 Midwest    1
Name: Region, dtype: int64
##################################################
679 Midwest    1
Name: Region, dtype: int64
##################################################
680 Midwest    7
Name: Region, dtype: int64
##################################################
681 Midwest    15
Name: Region, dtype: int64
##################################################
684 Midwest    3
Name: Region, dtype: int64
##################################################
685 Midwest    3
Name: Region, dtype: int64
##################################################
686 Midwest    2
Name: Region, dtype: int64
##################################################
687 Midwest    2
Name: Region, dtype: int64
##################################################
688 Midwest    1
Name: Region, dtype: int64
##################################################
689 Midwest    3
Name: Region, dtype: int64
##################################################
691 Midwest    3
Name: Region, dtype: int64
##################################################
693 Midwest    1
Name: Region, dtype: int64
##################################################
700 South    18
Name: Region, dtype: int64
##################################################
701 South    25
Name: Region, dtype: int64
##################################################
703 South    3
Name: Region, dtype: int64
##################################################
704 South    16
Name: Region, dtype: int64
##################################################
705 South    16
Name: Region, dtype: int64
##################################################
706 South    10
Name: Region, dtype: int64
##################################################
707 South    9
Name: Region, dtype: int64
##################################################
708 South    6
Name: Region, dtype: int64
##################################################
710 South    7
Name: Region, dtype: int64
##################################################
711 South    9
Name: Region, dtype: int64
##################################################
712 South    11
Name: Region, dtype: int64
##################################################
713 South    4
Name: Region, dtype: int64
##################################################
714 South    6
Name: Region, dtype: int64
##################################################
716 South    4
Name: Region, dtype: int64
##################################################
718 South    4
Name: Region, dtype: int64
##################################################
719 South    5
Name: Region, dtype: int64
##################################################
720 South    8
Name: Region, dtype: int64
##################################################
721 South    6
Name: Region, dtype: int64
##################################################
722 Midwest    1
South      3
Name: Region, dtype: int64
##################################################
723 South    9
Name: Region, dtype: int64
##################################################
724 South    1
Name: Region, dtype: int64
##################################################
725 South    1
Name: Region, dtype: int64
##################################################
726 South    3
Name: Region, dtype: int64
##################################################
727 South    12
Name: Region, dtype: int64
##################################################
728 South    2
Name: Region, dtype: int64
##################################################
729 West     1
South    5
Name: Region, dtype: int64
##################################################
730 South    20
Name: Region, dtype: int64
##################################################
731 South    19
Name: Region, dtype: int64
##################################################
735 South    2
Name: Region, dtype: int64
##################################################
737 South    3
Name: Region, dtype: int64
##################################################
738 South    1
Name: Region, dtype: int64
##################################################
740 South    16
Name: Region, dtype: int64
##################################################
741 South    8
Name: Region, dtype: int64
##################################################
743 South    2
Name: Region, dtype: int64
##################################################
744 South    7
Name: Region, dtype: int64
##################################################
745 South    3
Name: Region, dtype: int64
##################################################
746 South    2
Name: Region, dtype: int64
##################################################
747 South    2
Name: Region, dtype: int64
##################################################
748 South    5
Name: Region, dtype: int64
##################################################
749 South    3
Name: Region, dtype: int64
##################################################
750 South    96
Name: Region, dtype: int64
##################################################
751 South    25
Name: Region, dtype: int64
##################################################
752 South    47
Name: Region, dtype: int64
##################################################
754 South    9
Name: Region, dtype: int64
##################################################
755 South    6
Name: Region, dtype: int64
##################################################
756 South    8
Name: Region, dtype: int64
##################################################
757 South    12
Name: Region, dtype: int64
##################################################
758 South    3
Name: Region, dtype: int64
##################################################
759 South    11
Name: Region, dtype: int64
##################################################
760 South    59
Name: Region, dtype: int64
##################################################
761 South    38
Name: Region, dtype: int64
##################################################
762 South    19
Name: Region, dtype: int64
##################################################
763 South    9
Name: Region, dtype: int64
##################################################
764 South    4
Name: Region, dtype: int64
##################################################
765 South    11
Name: Region, dtype: int64
##################################################
766 South    9
Name: Region, dtype: int64
##################################################
767 South    5
Name: Region, dtype: int64
##################################################
768 South    2
Name: Region, dtype: int64
##################################################
769 South    7
Name: Region, dtype: int64
##################################################
770 Northeast      1
South        131
Name: Region, dtype: int64
##################################################
772 South    3
Name: Region, dtype: int64
##################################################
773 Northeast     1
South        58
Name: Region, dtype: int64
##################################################
774 South    53
Name: Region, dtype: int64
##################################################
775 South    58
Name: Region, dtype: int64
##################################################
776 South    11
Name: Region, dtype: int64
##################################################
777 South    4
Name: Region, dtype: int64
##################################################
778 South    19
Name: Region, dtype: int64
##################################################
779 South    5
Name: Region, dtype: int64
##################################################
780 South    22
Name: Region, dtype: int64
##################################################
781 South    13
Name: Region, dtype: int64
##################################################
782 South    72
Name: Region, dtype: int64
##################################################
783 South    10
Name: Region, dtype: int64
##################################################
784 South    17
Name: Region, dtype: int64
##################################################
785 South    49
Name: Region, dtype: int64
##################################################
786 South    30
Name: Region, dtype: int64
##################################################
787 South    41
Name: Region, dtype: int64
##################################################
788 South    10
Name: Region, dtype: int64
##################################################
789 South    4
Name: Region, dtype: int64
##################################################
790 South    17
Name: Region, dtype: int64
##################################################
791 South    20
Name: Region, dtype: int64
##################################################
792 South    1
Name: Region, dtype: int64
##################################################
793 South    15
Name: Region, dtype: int64
##################################################
794 South    25
Name: Region, dtype: int64
##################################################
795 South    2
Name: Region, dtype: int64
##################################################
796 South    2
Name: Region, dtype: int64
##################################################
797 South    19
Name: Region, dtype: int64
##################################################
798 South    7
Name: Region, dtype: int64
##################################################
799 South    40
Name: Region, dtype: int64
##################################################
800 Northeast     1
West         63
Name: Region, dtype: int64
##################################################
801 West    68
Name: Region, dtype: int64
##################################################
802 West    78
Name: Region, dtype: int64
##################################################
803 West    10
Name: Region, dtype: int64
##################################################
804 West    22
Name: Region, dtype: int64
##################################################
805 West    24
Name: Region, dtype: int64
##################################################
806 West    10
Name: Region, dtype: int64
##################################################
807 West    1
Name: Region, dtype: int64
##################################################
808 West    10
Name: Region, dtype: int64
##################################################
809 South     1
West     30
Name: Region, dtype: int64
##################################################
810 West    7
Name: Region, dtype: int64
##################################################
811 West    5
Name: Region, dtype: int64
##################################################
812 West    3
Name: Region, dtype: int64
##################################################
813 West    3
Name: Region, dtype: int64
##################################################
814 West    9
Name: Region, dtype: int64
##################################################
815 West    13
Name: Region, dtype: int64
##################################################
816 West    9
Name: Region, dtype: int64
##################################################
826 West    2
Name: Region, dtype: int64
##################################################
827 West    1
Name: Region, dtype: int64
##################################################
828 West    1
Name: Region, dtype: int64
##################################################
832 West    10
Name: Region, dtype: int64
##################################################
833 West    10
Name: Region, dtype: int64
##################################################
834 West    10
Name: Region, dtype: int64
##################################################
835 West    1
Name: Region, dtype: int64
##################################################
836 West    31
Name: Region, dtype: int64
##################################################
837 West    18
Name: Region, dtype: int64
##################################################
838 West    13
Name: Region, dtype: int64
##################################################
840 West    12
Name: Region, dtype: int64
##################################################
841 West    11
Name: Region, dtype: int64
##################################################
844 South    1
West     5
Name: Region, dtype: int64
##################################################
846 West    3
Name: Region, dtype: int64
##################################################
847 West    4
Name: Region, dtype: int64
##################################################
850 South     1
West     50
Name: Region, dtype: int64
##################################################
851 West    10
Name: Region, dtype: int64
##################################################
852 Midwest     1
West       57
Name: Region, dtype: int64
##################################################
853 Northeast     1
Midwest       1
West         48
Name: Region, dtype: int64
##################################################
855 West    2
Name: Region, dtype: int64
##################################################
856 West    12
Name: Region, dtype: int64
##################################################
857 West    38
Name: Region, dtype: int64
##################################################
859 West    2
Name: Region, dtype: int64
##################################################
860 West    1
Name: Region, dtype: int64
##################################################
863 West    5
Name: Region, dtype: int64
##################################################
864 West    1
Name: Region, dtype: int64
##################################################
870 West    18
Name: Region, dtype: int64
##################################################
871 South     2
West     56
Name: Region, dtype: int64
##################################################
873 West    3
Name: Region, dtype: int64
##################################################
874 West    5
Name: Region, dtype: int64
##################################################
875 West    24
Name: Region, dtype: int64
##################################################
877 West    6
Name: Region, dtype: int64
##################################################
880 West    13
Name: Region, dtype: int64
##################################################
881 West    1
Name: Region, dtype: int64
##################################################
882 West    11
Name: Region, dtype: int64
##################################################
883 South    1
West     5
Name: Region, dtype: int64
##################################################
890 West    12
Name: Region, dtype: int64
##################################################
891 West    30
Name: Region, dtype: int64
##################################################
894 West    10
Name: Region, dtype: int64
##################################################
895 West    7
Name: Region, dtype: int64
##################################################
897 West    1
Name: Region, dtype: int64
##################################################
900 South      1
West     236
Name: Region, dtype: int64
##################################################
902 South      1
West     114
Name: Region, dtype: int64
##################################################
903 West    5
Name: Region, dtype: int64
##################################################
904 West    5
Name: Region, dtype: int64
##################################################
905 West    16
Name: Region, dtype: int64
##################################################
906 West    72
Name: Region, dtype: int64
##################################################
907 West    63
Name: Region, dtype: int64
##################################################
908 West    36
Name: Region, dtype: int64
##################################################
910 West    32
Name: Region, dtype: int64
##################################################
911 South     1
West     20
Name: Region, dtype: int64
##################################################
912 West    30
Name: Region, dtype: int64
##################################################
913 South      2
West     123
Name: Region, dtype: int64
##################################################
914 West    23
Name: Region, dtype: int64
##################################################
915 West    10
Name: Region, dtype: int64
##################################################
916 West    17
Name: Region, dtype: int64
##################################################
917 West    170
Name: Region, dtype: int64
##################################################
918 West    11
Name: Region, dtype: int64
##################################################
919 West    25
Name: Region, dtype: int64
##################################################
920 West    79
Name: Region, dtype: int64
##################################################
921 West    49
Name: Region, dtype: int64
##################################################
922 West    49
Name: Region, dtype: int64
##################################################
923 South      1
West     102
Name: Region, dtype: int64
##################################################
924 West    18
Name: Region, dtype: int64
##################################################
925 West    86
Name: Region, dtype: int64
##################################################
926 West    118
Name: Region, dtype: int64
##################################################
927 Northeast     1
West         32
Name: Region, dtype: int64
##################################################
928 West    96
Name: Region, dtype: int64
##################################################
930 West    34
Name: Region, dtype: int64
##################################################
931 West    13
Name: Region, dtype: int64
##################################################
932 West    38
Name: Region, dtype: int64
##################################################
933 West    24
Name: Region, dtype: int64
##################################################
934 West    31
Name: Region, dtype: int64
##################################################
935 West    36
Name: Region, dtype: int64
##################################################
936 West    36
Name: Region, dtype: int64
##################################################
937 West    23
Name: Region, dtype: int64
##################################################
939 West    27
Name: Region, dtype: int64
##################################################
940 West    34
Name: Region, dtype: int64
##################################################
941 West    37
Name: Region, dtype: int64
##################################################
943 West    4
Name: Region, dtype: int64
##################################################
944 West    3
Name: Region, dtype: int64
##################################################
945 Midwest     1
West       67
Name: Region, dtype: int64
##################################################
946 West    21
Name: Region, dtype: int64
##################################################
947 West    9
Name: Region, dtype: int64
##################################################
948 West    6
Name: Region, dtype: int64
##################################################
949 South     1
West     20
Name: Region, dtype: int64
##################################################
950 West    50
Name: Region, dtype: int64
##################################################
951 West    29
Name: Region, dtype: int64
##################################################
952 West    23
Name: Region, dtype: int64
##################################################
953 West    49
Name: Region, dtype: int64
##################################################
954 West    18
Name: Region, dtype: int64
##################################################
955 West    13
Name: Region, dtype: int64
##################################################
956 West    55
Name: Region, dtype: int64
##################################################
957 West    11
Name: Region, dtype: int64
##################################################
958 West    35
Name: Region, dtype: int64
##################################################
959 West    41
Name: Region, dtype: int64
##################################################
960 West    16
Name: Region, dtype: int64
##################################################
961 West    5
Name: Region, dtype: int64
##################################################
967 West    12
Name: Region, dtype: int64
##################################################
968 South    1
West     9
Name: Region, dtype: int64
##################################################
970 West    12
Name: Region, dtype: int64
##################################################
971 West    9
Name: Region, dtype: int64
##################################################
972 West    15
Name: Region, dtype: int64
##################################################
973 West    12
Name: Region, dtype: int64
##################################################
974 West    19
Name: Region, dtype: int64
##################################################
975 West    12
Name: Region, dtype: int64
##################################################
976 West    2
Name: Region, dtype: int64
##################################################
977 West    1
Name: Region, dtype: int64
##################################################
978 West    2
Name: Region, dtype: int64
##################################################
980 South     1
West     47
Name: Region, dtype: int64
##################################################
981 West    27
Name: Region, dtype: int64
##################################################
982 West    27
Name: Region, dtype: int64
##################################################
983 West    19
Name: Region, dtype: int64
##################################################
984 South     1
West     14
Name: Region, dtype: int64
##################################################
985 West    5
Name: Region, dtype: int64
##################################################
986 West    12
Name: Region, dtype: int64
##################################################
988 West    10
Name: Region, dtype: int64
##################################################
989 West    3
Name: Region, dtype: int64
##################################################
990 West    7
Name: Region, dtype: int64
##################################################
991 Midwest    1
West       8
Name: Region, dtype: int64
##################################################
992 West    12
Name: Region, dtype: int64
##################################################
993 West    6
Name: Region, dtype: int64
##################################################
994 West    1
Name: Region, dtype: int64
##################################################
995 West    2
Name: Region, dtype: int64
##################################################
996 West    2
Name: Region, dtype: int64
##################################################
998 West    1
Name: Region, dtype: int64
##################################################
999 West    1
Name: Region, dtype: int64
In [40]:
test["Region"] = test.apply(lambda row: stocker_Region.get(row["patient_zip3"], row["Region"]), axis=1)
In [41]:
test.loc[5773 , "Region"] = 'Midwest'
test.loc[5773 , "Division"] = 'West North Central'
In [42]:
stocker_Division  = dict()
for zp in patient_zip3 : 
    stocker_Division[zp] = train[train['patient_zip3'] == zp].Division.value_counts().sort_values().index[-1]
    print("#"*50)
    print(zp , train[train['patient_zip3'] == zp].Division.value_counts().sort_values())

    
for i in train.index:
    train.at[i, "Division"] = stocker_Division.get(train.at[i, "patient_zip3"], None)
##################################################
101 Middle Atlantic    2
Name: Division, dtype: int64
##################################################
103 South Atlantic      1
Middle Atlantic    34
Name: Division, dtype: int64
##################################################
104 South Atlantic       2
Middle Atlantic    110
Name: Division, dtype: int64
##################################################
105 Middle Atlantic    33
Name: Division, dtype: int64
##################################################
106 Middle Atlantic    5
Name: Division, dtype: int64
##################################################
107 Middle Atlantic    11
Name: Division, dtype: int64
##################################################
108 Middle Atlantic    7
Name: Division, dtype: int64
##################################################
109 South Atlantic      1
Middle Atlantic    16
Name: Division, dtype: int64
##################################################
110 Middle Atlantic    15
Name: Division, dtype: int64
##################################################
111 Middle Atlantic    13
Name: Division, dtype: int64
##################################################
112 Pacific                 1
West South Central      1
New England             2
Middle Atlantic       188
Name: Division, dtype: int64
##################################################
113 Pacific             1
South Atlantic      2
Middle Atlantic    68
Name: Division, dtype: int64
##################################################
114 South Atlantic      2
Middle Atlantic    55
Name: Division, dtype: int64
##################################################
115 Middle Atlantic    40
Name: Division, dtype: int64
##################################################
116 Middle Atlantic    8
Name: Division, dtype: int64
##################################################
117 South Atlantic      4
Middle Atlantic    67
Name: Division, dtype: int64
##################################################
118 Middle Atlantic    1
Mountain           1
Name: Division, dtype: int64
##################################################
119 South Atlantic      1
Middle Atlantic    13
Name: Division, dtype: int64
##################################################
120 Middle Atlantic    27
Name: Division, dtype: int64
##################################################
121 Middle Atlantic    25
Name: Division, dtype: int64
##################################################
122 Pacific             1
Middle Atlantic    13
Name: Division, dtype: int64
##################################################
123 Middle Atlantic    14
Name: Division, dtype: int64
##################################################
124 Middle Atlantic    11
Name: Division, dtype: int64
##################################################
125 Middle Atlantic    23
Name: Division, dtype: int64
##################################################
126 Middle Atlantic    3
Name: Division, dtype: int64
##################################################
127 South Atlantic     1
Middle Atlantic    7
Name: Division, dtype: int64
##################################################
128 Middle Atlantic    19
Name: Division, dtype: int64
##################################################
129 Middle Atlantic    4
Name: Division, dtype: int64
##################################################
130 Middle Atlantic    5
Name: Division, dtype: int64
##################################################
131 Middle Atlantic    2
Name: Division, dtype: int64
##################################################
132 Middle Atlantic    6
Name: Division, dtype: int64
##################################################
133 Middle Atlantic    3
Name: Division, dtype: int64
##################################################
134 Middle Atlantic    7
Name: Division, dtype: int64
##################################################
135 Middle Atlantic    2
Name: Division, dtype: int64
##################################################
136 Middle Atlantic    9
Name: Division, dtype: int64
##################################################
137 Middle Atlantic    4
Name: Division, dtype: int64
##################################################
138 Middle Atlantic    7
Name: Division, dtype: int64
##################################################
139 Middle Atlantic    1
Name: Division, dtype: int64
##################################################
140 Middle Atlantic    39
Name: Division, dtype: int64
##################################################
141 Middle Atlantic    25
Name: Division, dtype: int64
##################################################
142 Middle Atlantic    50
Name: Division, dtype: int64
##################################################
143 Middle Atlantic    6
Name: Division, dtype: int64
##################################################
144 Middle Atlantic    9
Name: Division, dtype: int64
##################################################
145 Middle Atlantic    11
Name: Division, dtype: int64
##################################################
146 Middle Atlantic    23
Name: Division, dtype: int64
##################################################
147 Middle Atlantic    8
Name: Division, dtype: int64
##################################################
148 Middle Atlantic    5
Name: Division, dtype: int64
##################################################
149 Middle Atlantic    1
Name: Division, dtype: int64
##################################################
150 Middle Atlantic    6
Name: Division, dtype: int64
##################################################
151 Middle Atlantic    11
Name: Division, dtype: int64
##################################################
152 Middle Atlantic    11
Name: Division, dtype: int64
##################################################
154 Middle Atlantic    2
Name: Division, dtype: int64
##################################################
155 Middle Atlantic    1
Name: Division, dtype: int64
##################################################
156 Middle Atlantic    9
Name: Division, dtype: int64
##################################################
157 Middle Atlantic    1
Name: Division, dtype: int64
##################################################
158 Middle Atlantic    2
Name: Division, dtype: int64
##################################################
159 Middle Atlantic    2
Name: Division, dtype: int64
##################################################
160 Middle Atlantic    5
Name: Division, dtype: int64
##################################################
161 Middle Atlantic    2
Name: Division, dtype: int64
##################################################
162 Middle Atlantic    1
Name: Division, dtype: int64
##################################################
163 Middle Atlantic    1
Name: Division, dtype: int64
##################################################
164 Middle Atlantic    4
Name: Division, dtype: int64
##################################################
165 Middle Atlantic    7
Name: Division, dtype: int64
##################################################
166 Middle Atlantic    3
Name: Division, dtype: int64
##################################################
168 Middle Atlantic    2
Name: Division, dtype: int64
##################################################
169 Middle Atlantic    2
Name: Division, dtype: int64
##################################################
170 West North Central     1
Middle Atlantic       20
Name: Division, dtype: int64
##################################################
171 West South Central    1
Middle Atlantic       6
Name: Division, dtype: int64
##################################################
172 Middle Atlantic    4
Name: Division, dtype: int64
##################################################
173 Middle Atlantic    10
Name: Division, dtype: int64
##################################################
174 Middle Atlantic    4
Name: Division, dtype: int64
##################################################
175 Middle Atlantic    9
Name: Division, dtype: int64
##################################################
176 Middle Atlantic    6
Name: Division, dtype: int64
##################################################
177 Middle Atlantic    7
Name: Division, dtype: int64
##################################################
178 Middle Atlantic    13
Name: Division, dtype: int64
##################################################
179 Middle Atlantic    6
Name: Division, dtype: int64
##################################################
180 Middle Atlantic    24
Name: Division, dtype: int64
##################################################
181 Middle Atlantic    9
Name: Division, dtype: int64
##################################################
182 Middle Atlantic    5
Name: Division, dtype: int64
##################################################
183 Middle Atlantic    15
Name: Division, dtype: int64
##################################################
184 Middle Atlantic    6
Name: Division, dtype: int64
##################################################
185 Middle Atlantic    5
Name: Division, dtype: int64
##################################################
186 Middle Atlantic    11
Name: Division, dtype: int64
##################################################
187 Middle Atlantic    3
Name: Division, dtype: int64
##################################################
189 Middle Atlantic    32
Name: Division, dtype: int64
##################################################
190 South Atlantic         1
East South Central     1
Middle Atlantic       62
Name: Division, dtype: int64
##################################################
191 South Atlantic         1
West South Central     2
Middle Atlantic       88
Name: Division, dtype: int64
##################################################
193 Pacific             1
Middle Atlantic    17
Name: Division, dtype: int64
##################################################
194 Middle Atlantic    37
Name: Division, dtype: int64
##################################################
195 Middle Atlantic    3
Name: Division, dtype: int64
##################################################
196 South Atlantic     1
Middle Atlantic    5
Name: Division, dtype: int64
##################################################
197 South Atlantic    7
Name: Division, dtype: int64
##################################################
198 South Atlantic    6
Name: Division, dtype: int64
##################################################
199 South Atlantic    16
Name: Division, dtype: int64
##################################################
200 South Atlantic    20
Name: Division, dtype: int64
##################################################
201 South Atlantic    23
Name: Division, dtype: int64
##################################################
206 South Atlantic    4
Name: Division, dtype: int64
##################################################
207 South Atlantic    11
Name: Division, dtype: int64
##################################################
208 New England        1
South Atlantic    11
Name: Division, dtype: int64
##################################################
209 West South Central    1
South Atlantic        3
Name: Division, dtype: int64
##################################################
210 South Atlantic    7
Name: Division, dtype: int64
##################################################
211 South Atlantic    8
Name: Division, dtype: int64
##################################################
212 South Atlantic    14
Name: Division, dtype: int64
##################################################
215 South Atlantic    3
Name: Division, dtype: int64
##################################################
216 South Atlantic    2
Name: Division, dtype: int64
##################################################
217 South Atlantic    8
Name: Division, dtype: int64
##################################################
220 South Atlantic    11
Name: Division, dtype: int64
##################################################
221 South Atlantic    15
Name: Division, dtype: int64
##################################################
222 South Atlantic    5
Name: Division, dtype: int64
##################################################
223 South Atlantic    6
Name: Division, dtype: int64
##################################################
224 South Atlantic    8
Name: Division, dtype: int64
##################################################
225 South Atlantic    6
Name: Division, dtype: int64
##################################################
226 South Atlantic    7
Name: Division, dtype: int64
##################################################
227 South Atlantic    6
Name: Division, dtype: int64
##################################################
228 South Atlantic    10
Name: Division, dtype: int64
##################################################
229 South Atlantic    16
Name: Division, dtype: int64
##################################################
230 South Atlantic    16
Name: Division, dtype: int64
##################################################
231 South Atlantic    17
Name: Division, dtype: int64
##################################################
232 South Atlantic    28
Name: Division, dtype: int64
##################################################
233 Mountain           1
South Atlantic    19
Name: Division, dtype: int64
##################################################
234 South Atlantic    30
Name: Division, dtype: int64
##################################################
235 East North Central     1
Middle Atlantic        1
South Atlantic        12
Name: Division, dtype: int64
##################################################
236 South Atlantic    21
Name: Division, dtype: int64
##################################################
237 South Atlantic    3
Name: Division, dtype: int64
##################################################
238 South Atlantic    25
Name: Division, dtype: int64
##################################################
239 South Atlantic    9
Name: Division, dtype: int64
##################################################
240 South Atlantic    17
Name: Division, dtype: int64
##################################################
241 South Atlantic    11
Name: Division, dtype: int64
##################################################
242 South Atlantic    7
Name: Division, dtype: int64
##################################################
243 South Atlantic    6
Name: Division, dtype: int64
##################################################
244 South Atlantic    7
Name: Division, dtype: int64
##################################################
245 South Atlantic    18
Name: Division, dtype: int64
##################################################
246 South Atlantic    5
Name: Division, dtype: int64
##################################################
247 South Atlantic    1
Name: Division, dtype: int64
##################################################
248 South Atlantic    3
Name: Division, dtype: int64
##################################################
251 South Atlantic    1
Name: Division, dtype: int64
##################################################
252 South Atlantic    1
Name: Division, dtype: int64
##################################################
253 South Atlantic    2
Name: Division, dtype: int64
##################################################
254 South Atlantic    2
Name: Division, dtype: int64
##################################################
255 South Atlantic    1
Name: Division, dtype: int64
##################################################
256 South Atlantic    1
Name: Division, dtype: int64
##################################################
259 South Atlantic    2
Name: Division, dtype: int64
##################################################
260 South Atlantic    3
Name: Division, dtype: int64
##################################################
261 South Atlantic    1
Name: Division, dtype: int64
##################################################
262 South Atlantic    3
Name: Division, dtype: int64
##################################################
263 South Atlantic    1
Name: Division, dtype: int64
##################################################
264 South Atlantic    1
Name: Division, dtype: int64
##################################################
265 South Atlantic    1
Name: Division, dtype: int64
##################################################
267 South Atlantic    3
Name: Division, dtype: int64
##################################################
270 South Atlantic    7
Name: Division, dtype: int64
##################################################
271 South Atlantic    9
Name: Division, dtype: int64
##################################################
272 South Atlantic    12
Name: Division, dtype: int64
##################################################
273 South Atlantic    4
Name: Division, dtype: int64
##################################################
274 South Atlantic    5
Name: Division, dtype: int64
##################################################
275 Middle Atlantic     1
South Atlantic     22
Name: Division, dtype: int64
##################################################
276 South Atlantic    9
Name: Division, dtype: int64
##################################################
277 South Atlantic    4
Name: Division, dtype: int64
##################################################
278 South Atlantic    11
Name: Division, dtype: int64
##################################################
279 South Atlantic    5
Name: Division, dtype: int64
##################################################
280 South Atlantic    16
Name: Division, dtype: int64
##################################################
281 South Atlantic    7
Name: Division, dtype: int64
##################################################
282 South Atlantic    20
Name: Division, dtype: int64
##################################################
283 South Atlantic    14
Name: Division, dtype: int64
##################################################
284 South Atlantic    9
Name: Division, dtype: int64
##################################################
285 South Atlantic    6
Name: Division, dtype: int64
##################################################
286 South Atlantic    8
Name: Division, dtype: int64
##################################################
287 South Atlantic    11
Name: Division, dtype: int64
##################################################
288 South Atlantic    2
Name: Division, dtype: int64
##################################################
290 South Atlantic    12
Name: Division, dtype: int64
##################################################
291 South Atlantic    10
Name: Division, dtype: int64
##################################################
292 South Atlantic    8
Name: Division, dtype: int64
##################################################
293 South Atlantic    7
Name: Division, dtype: int64
##################################################
294 South Atlantic    14
Name: Division, dtype: int64
##################################################
295 South Atlantic    11
Name: Division, dtype: int64
##################################################
296 South Atlantic    21
Name: Division, dtype: int64
##################################################
297 South Atlantic    13
Name: Division, dtype: int64
##################################################
298 South Atlantic    7
Name: Division, dtype: int64
##################################################
299 South Atlantic    6
Name: Division, dtype: int64
##################################################
300 West South Central      1
South Atlantic        119
Name: Division, dtype: int64
##################################################
301 South Atlantic    59
Name: Division, dtype: int64
##################################################
302 South Atlantic    53
Name: Division, dtype: int64
##################################################
303 South Atlantic    48
Name: Division, dtype: int64
##################################################
304 South Atlantic    13
Name: Division, dtype: int64
##################################################
305 South Atlantic    33
Name: Division, dtype: int64
##################################################
306 South Atlantic    25
Name: Division, dtype: int64
##################################################
307 West South Central     1
South Atlantic        14
Name: Division, dtype: int64
##################################################
308 South Atlantic    7
Name: Division, dtype: int64
##################################################
309 South Atlantic    13
Name: Division, dtype: int64
##################################################
310 South Atlantic    28
Name: Division, dtype: int64
##################################################
312 South Atlantic    6
Name: Division, dtype: int64
##################################################
313 West South Central    1
South Atlantic        9
Name: Division, dtype: int64
##################################################
314 South Atlantic    22
Name: Division, dtype: int64
##################################################
315 South Atlantic    27
Name: Division, dtype: int64
##################################################
316 South Atlantic    14
Name: Division, dtype: int64
##################################################
317 South Atlantic    35
Name: Division, dtype: int64
##################################################
318 East South Central    1
South Atlantic        4
Name: Division, dtype: int64
##################################################
319 South Atlantic    9
Name: Division, dtype: int64
##################################################
320 Middle Atlantic     1
South Atlantic     11
Name: Division, dtype: int64
##################################################
321 Mountain           1
South Atlantic    14
Name: Division, dtype: int64
##################################################
322 South Atlantic    28
Name: Division, dtype: int64
##################################################
323 South Atlantic    7
Name: Division, dtype: int64
##################################################
324 South Atlantic    11
Name: Division, dtype: int64
##################################################
325 South Atlantic    9
Name: Division, dtype: int64
##################################################
326 East South Central    1
South Atlantic        2
Name: Division, dtype: int64
##################################################
327 East North Central     2
South Atlantic        17
Name: Division, dtype: int64
##################################################
328 South Atlantic    30
Name: Division, dtype: int64
##################################################
329 South Atlantic    15
Name: Division, dtype: int64
##################################################
330 South Atlantic    66
Name: Division, dtype: int64
##################################################
331 South Atlantic    91
Name: Division, dtype: int64
##################################################
332 South Atlantic    1
Name: Division, dtype: int64
##################################################
333 South Atlantic    20
Name: Division, dtype: int64
##################################################
334 Middle Atlantic     1
South Atlantic     33
Name: Division, dtype: int64
##################################################
335 South Atlantic    22
Name: Division, dtype: int64
##################################################
336 South Atlantic    34
Name: Division, dtype: int64
##################################################
337 South Atlantic    30
Name: Division, dtype: int64
##################################################
338 South Atlantic    26
Name: Division, dtype: int64
##################################################
339 South Atlantic    23
Name: Division, dtype: int64
##################################################
341 South Atlantic    5
Name: Division, dtype: int64
##################################################
342 South Atlantic    33
Name: Division, dtype: int64
##################################################
344 South Atlantic    6
Name: Division, dtype: int64
##################################################
346 South Atlantic    26
Name: Division, dtype: int64
##################################################
347 East North Central     1
Middle Atlantic        1
South Atlantic        17
Name: Division, dtype: int64
##################################################
349 South Atlantic    15
Name: Division, dtype: int64
##################################################
350 East South Central    5
Name: Division, dtype: int64
##################################################
351 East South Central    1
Name: Division, dtype: int64
##################################################
352 East South Central    4
Name: Division, dtype: int64
##################################################
354 East South Central    2
Name: Division, dtype: int64
##################################################
356 East South Central    7
Name: Division, dtype: int64
##################################################
357 East South Central    5
Name: Division, dtype: int64
##################################################
358 East South Central    3
Name: Division, dtype: int64
##################################################
359 South Atlantic        1
East South Central    3
Name: Division, dtype: int64
##################################################
360 East South Central    2
Name: Division, dtype: int64
##################################################
361 East South Central    1
Name: Division, dtype: int64
##################################################
363 East South Central    2
Name: Division, dtype: int64
##################################################
365 South Atlantic        1
East South Central    5
Name: Division, dtype: int64
##################################################
366 East South Central    2
Name: Division, dtype: int64
##################################################
367 East South Central    1
Name: Division, dtype: int64
##################################################
368 East South Central    7
Name: Division, dtype: int64
##################################################
370 East North Central     1
East South Central    15
Name: Division, dtype: int64
##################################################
371 South Atlantic         1
East South Central    13
Name: Division, dtype: int64
##################################################
372 East South Central    3
Name: Division, dtype: int64
##################################################
373 East South Central    4
Name: Division, dtype: int64
##################################################
374 East South Central    3
Name: Division, dtype: int64
##################################################
376 East South Central    4
Name: Division, dtype: int64
##################################################
377 East South Central    7
Name: Division, dtype: int64
##################################################
378 East South Central    10
Name: Division, dtype: int64
##################################################
379 East South Central    4
Name: Division, dtype: int64
##################################################
380 East South Central    7
Name: Division, dtype: int64
##################################################
381 East South Central    21
Name: Division, dtype: int64
##################################################
382 East South Central    3
Name: Division, dtype: int64
##################################################
383 East South Central    6
Name: Division, dtype: int64
##################################################
384 East South Central    6
Name: Division, dtype: int64
##################################################
385 East South Central    5
Name: Division, dtype: int64
##################################################
386 East South Central    9
Name: Division, dtype: int64
##################################################
387 East South Central    4
Name: Division, dtype: int64
##################################################
388 East South Central    3
Name: Division, dtype: int64
##################################################
389 East South Central    3
Name: Division, dtype: int64
##################################################
390 East South Central    11
Name: Division, dtype: int64
##################################################
391 East South Central    12
Name: Division, dtype: int64
##################################################
392 East South Central    12
Name: Division, dtype: int64
##################################################
393 East South Central    2
Name: Division, dtype: int64
##################################################
394 East South Central    6
Name: Division, dtype: int64
##################################################
395 East South Central    8
Name: Division, dtype: int64
##################################################
396 East South Central    3
Name: Division, dtype: int64
##################################################
397 East South Central    1
Name: Division, dtype: int64
##################################################
398 South Atlantic    8
Name: Division, dtype: int64
##################################################
400 East South Central    20
Name: Division, dtype: int64
##################################################
401 East South Central    8
Name: Division, dtype: int64
##################################################
402 South Atlantic         1
East North Central     1
East South Central    43
Name: Division, dtype: int64
##################################################
403 East South Central    14
Name: Division, dtype: int64
##################################################
404 East South Central    15
Name: Division, dtype: int64
##################################################
405 East South Central    30
Name: Division, dtype: int64
##################################################
406 East South Central    3
Name: Division, dtype: int64
##################################################
407 East South Central    7
Name: Division, dtype: int64
##################################################
408 East South Central    2
Name: Division, dtype: int64
##################################################
409 East South Central    4
Name: Division, dtype: int64
##################################################
410 East South Central    23
Name: Division, dtype: int64
##################################################
411 East South Central    8
Name: Division, dtype: int64
##################################################
412 East South Central    2
Name: Division, dtype: int64
##################################################
413 East South Central    2
Name: Division, dtype: int64
##################################################
414 East South Central    2
Name: Division, dtype: int64
##################################################
415 East South Central    3
Name: Division, dtype: int64
##################################################
416 East South Central    1
Name: Division, dtype: int64
##################################################
417 East South Central    3
Name: Division, dtype: int64
##################################################
418 East South Central    3
Name: Division, dtype: int64
##################################################
420 East South Central    6
Name: Division, dtype: int64
##################################################
421 East South Central    13
Name: Division, dtype: int64
##################################################
422 East South Central    6
Name: Division, dtype: int64
##################################################
423 East South Central    13
Name: Division, dtype: int64
##################################################
424 East South Central    4
Name: Division, dtype: int64
##################################################
425 East South Central    3
Name: Division, dtype: int64
##################################################
426 East South Central    5
Name: Division, dtype: int64
##################################################
427 East South Central    11
Name: Division, dtype: int64
##################################################
430 East North Central    60
Name: Division, dtype: int64
##################################################
431 East North Central    26
Name: Division, dtype: int64
##################################################
432 East North Central    52
Name: Division, dtype: int64
##################################################
433 East North Central    9
Name: Division, dtype: int64
##################################################
434 East North Central    12
Name: Division, dtype: int64
##################################################
435 Mountain               1
East North Central    17
Name: Division, dtype: int64
##################################################
436 East North Central    22
Name: Division, dtype: int64
##################################################
437 East North Central    13
Name: Division, dtype: int64
##################################################
438 East North Central    4
Name: Division, dtype: int64
##################################################
439 East North Central    7
Name: Division, dtype: int64
##################################################
440 East North Central    72
Name: Division, dtype: int64
##################################################
441 East North Central    74
Name: Division, dtype: int64
##################################################
442 West South Central     1
East North Central    43
Name: Division, dtype: int64
##################################################
443 East North Central    26
Name: Division, dtype: int64
##################################################
444 East North Central    13
Name: Division, dtype: int64
##################################################
445 Middle Atlantic        1
East North Central    20
Name: Division, dtype: int64
##################################################
446 West North Central     1
East North Central    27
Name: Division, dtype: int64
##################################################
447 East North Central    15
Name: Division, dtype: int64
##################################################
448 East North Central    25
Name: Division, dtype: int64
##################################################
449 East North Central    8
Name: Division, dtype: int64
##################################################
450 South Atlantic         1
East North Central    26
Name: Division, dtype: int64
##################################################
451 East North Central    14
Name: Division, dtype: int64
##################################################
452 East North Central    35
Name: Division, dtype: int64
##################################################
453 East North Central    42
Name: Division, dtype: int64
##################################################
454 East North Central    35
Name: Division, dtype: int64
##################################################
455 East North Central    5
Name: Division, dtype: int64
##################################################
456 East North Central    14
Name: Division, dtype: int64
##################################################
457 East North Central    12
Name: Division, dtype: int64
##################################################
458 East North Central    20
Name: Division, dtype: int64
##################################################
460 East North Central    32
Name: Division, dtype: int64
##################################################
461 East North Central    29
Name: Division, dtype: int64
##################################################
462 East North Central    59
Name: Division, dtype: int64
##################################################
463 East North Central    34
Name: Division, dtype: int64
##################################################
464 East North Central    7
Name: Division, dtype: int64
##################################################
465 East North Central    24
Name: Division, dtype: int64
##################################################
466 East North Central    6
Name: Division, dtype: int64
##################################################
467 East North Central    13
Name: Division, dtype: int64
##################################################
468 East North Central    13
Name: Division, dtype: int64
##################################################
469 East North Central    15
Name: Division, dtype: int64
##################################################
470 East North Central    8
Name: Division, dtype: int64
##################################################
471 East South Central     1
East North Central    17
Name: Division, dtype: int64
##################################################
472 East North Central    13
Name: Division, dtype: int64
##################################################
473 West South Central     1
East North Central    10
Name: Division, dtype: int64
##################################################
474 East North Central    11
Name: Division, dtype: int64
##################################################
475 East North Central    5
Name: Division, dtype: int64
##################################################
476 East North Central    2
Name: Division, dtype: int64
##################################################
477 East South Central    1
East North Central    2
Name: Division, dtype: int64
##################################################
478 East North Central    6
Name: Division, dtype: int64
##################################################
479 East North Central    10
Name: Division, dtype: int64
##################################################
480 East North Central    103
Name: Division, dtype: int64
##################################################
481 East North Central    131
Name: Division, dtype: int64
##################################################
482 Pacific                2
East North Central    96
Name: Division, dtype: int64
##################################################
483 East North Central    95
Name: Division, dtype: int64
##################################################
484 East North Central    37
Name: Division, dtype: int64
##################################################
485 East South Central     1
East North Central    18
Name: Division, dtype: int64
##################################################
486 East North Central    28
Name: Division, dtype: int64
##################################################
487 East North Central    11
Name: Division, dtype: int64
##################################################
488 South Atlantic         1
East North Central    48
Name: Division, dtype: int64
##################################################
489 East North Central    10
Name: Division, dtype: int64
##################################################
490 East North Central    57
Name: Division, dtype: int64
##################################################
491 Pacific               1
East North Central    7
Name: Division, dtype: int64
##################################################
492 East North Central    37
Name: Division, dtype: int64
##################################################
493 East North Central    34
Name: Division, dtype: int64
##################################################
494 East North Central    44
Name: Division, dtype: int64
##################################################
495 East North Central    36
Name: Division, dtype: int64
##################################################
496 East North Central    21
Name: Division, dtype: int64
##################################################
497 East North Central    18
Name: Division, dtype: int64
##################################################
498 East North Central    19
Name: Division, dtype: int64
##################################################
499 East North Central    7
Name: Division, dtype: int64
##################################################
500 West North Central    4
Name: Division, dtype: int64
##################################################
501 West North Central    4
Name: Division, dtype: int64
##################################################
502 West North Central    3
Name: Division, dtype: int64
##################################################
503 West North Central    7
Name: Division, dtype: int64
##################################################
504 West North Central    8
Name: Division, dtype: int64
##################################################
505 West North Central    6
Name: Division, dtype: int64
##################################################
506 West North Central    1
Name: Division, dtype: int64
##################################################
507 West North Central    4
Name: Division, dtype: int64
##################################################
510 West North Central    2
Name: Division, dtype: int64
##################################################
511 West North Central    5
Name: Division, dtype: int64
##################################################
512 West North Central    1
Name: Division, dtype: int64
##################################################
514 West North Central    1
Name: Division, dtype: int64
##################################################
515 West North Central    3
Name: Division, dtype: int64
##################################################
516 West North Central    2
Name: Division, dtype: int64
##################################################
520 West North Central    5
Name: Division, dtype: int64
##################################################
522 West North Central    7
Name: Division, dtype: int64
##################################################
523 West North Central    4
Name: Division, dtype: int64
##################################################
524 West North Central    5
Name: Division, dtype: int64
##################################################
525 West North Central    5
Name: Division, dtype: int64
##################################################
526 West North Central    1
Name: Division, dtype: int64
##################################################
527 West North Central    4
Name: Division, dtype: int64
##################################################
528 West North Central    4
Name: Division, dtype: int64
##################################################
530 East North Central    19
Name: Division, dtype: int64
##################################################
531 East North Central    37
Name: Division, dtype: int64
##################################################
532 West South Central     1
East North Central    20
Name: Division, dtype: int64
##################################################
534 East North Central    2
Name: Division, dtype: int64
##################################################
535 East North Central    24
Name: Division, dtype: int64
##################################################
537 East North Central    8
Name: Division, dtype: int64
##################################################
539 East North Central    5
Name: Division, dtype: int64
##################################################
540 East North Central    2
Name: Division, dtype: int64
##################################################
541 East North Central    13
Name: Division, dtype: int64
##################################################
542 East North Central    15
Name: Division, dtype: int64
##################################################
543 East North Central    7
Name: Division, dtype: int64
##################################################
544 East North Central    5
Name: Division, dtype: int64
##################################################
545 East North Central    3
Name: Division, dtype: int64
##################################################
546 East North Central    4
Name: Division, dtype: int64
##################################################
547 East North Central    7
Name: Division, dtype: int64
##################################################
548 East North Central    5
Name: Division, dtype: int64
##################################################
549 East North Central    32
Name: Division, dtype: int64
##################################################
550 West North Central    47
Name: Division, dtype: int64
##################################################
551 West North Central    39
Name: Division, dtype: int64
##################################################
553 East North Central     1
West North Central    62
Name: Division, dtype: int64
##################################################
554 West North Central    47
Name: Division, dtype: int64
##################################################
557 West North Central    13
Name: Division, dtype: int64
##################################################
558 West North Central    7
Name: Division, dtype: int64
##################################################
559 East North Central     1
West North Central    25
Name: Division, dtype: int64
##################################################
560 West North Central    37
Name: Division, dtype: int64
##################################################
561 West North Central    7
Name: Division, dtype: int64
##################################################
562 West North Central    19
Name: Division, dtype: int64
##################################################
563 West North Central    24
Name: Division, dtype: int64
##################################################
564 West North Central    10
Name: Division, dtype: int64
##################################################
565 West North Central    23
Name: Division, dtype: int64
##################################################
566 West North Central    6
Name: Division, dtype: int64
##################################################
567 West North Central    7
Name: Division, dtype: int64
##################################################
570 West North Central    2
Name: Division, dtype: int64
##################################################
573 West North Central    1
Name: Division, dtype: int64
##################################################
574 West North Central    1
Name: Division, dtype: int64
##################################################
577 West North Central    4
Name: Division, dtype: int64
##################################################
581 West North Central    3
Name: Division, dtype: int64
##################################################
582 West North Central    1
Name: Division, dtype: int64
##################################################
585 West North Central    1
Name: Division, dtype: int64
##################################################
587 West North Central    1
Name: Division, dtype: int64
##################################################
590 Mountain    2
Name: Division, dtype: int64
##################################################
591 Mountain    10
Name: Division, dtype: int64
##################################################
592 Mountain    1
Name: Division, dtype: int64
##################################################
593 Mountain    2
Name: Division, dtype: int64
##################################################
594 Mountain    6
Name: Division, dtype: int64
##################################################
596 Mountain    3
Name: Division, dtype: int64
##################################################
597 Mountain    6
Name: Division, dtype: int64
##################################################
598 Mountain    5
Name: Division, dtype: int64
##################################################
599 Mountain    9
Name: Division, dtype: int64
##################################################
600 East North Central    104
Name: Division, dtype: int64
##################################################
601 New England            1
East North Central    91
Name: Division, dtype: int64
##################################################
602 East North Central    9
Name: Division, dtype: int64
##################################################
603 East North Central    7
Name: Division, dtype: int64
##################################################
604 East North Central    96
Name: Division, dtype: int64
##################################################
605 South Atlantic         1
East North Central    99
Name: Division, dtype: int64
##################################################
606 East North Central    150
Name: Division, dtype: int64
##################################################
607 East North Central    7
Name: Division, dtype: int64
##################################################
608 East North Central    2
Name: Division, dtype: int64
##################################################
609 East North Central    13
Name: Division, dtype: int64
##################################################
610 East North Central    15
Name: Division, dtype: int64
##################################################
611 East North Central    10
Name: Division, dtype: int64
##################################################
612 East North Central    11
Name: Division, dtype: int64
##################################################
613 East North Central    9
Name: Division, dtype: int64
##################################################
614 East North Central    6
Name: Division, dtype: int64
##################################################
615 East North Central    14
Name: Division, dtype: int64
##################################################
616 East North Central    9
Name: Division, dtype: int64
##################################################
617 East North Central    18
Name: Division, dtype: int64
##################################################
618 East North Central    11
Name: Division, dtype: int64
##################################################
619 East North Central    7
Name: Division, dtype: int64
##################################################
620 East North Central    7
Name: Division, dtype: int64
##################################################
622 East North Central    18
Name: Division, dtype: int64
##################################################
623 East North Central    2
Name: Division, dtype: int64
##################################################
624 East North Central    6
Name: Division, dtype: int64
##################################################
625 East North Central    14
Name: Division, dtype: int64
##################################################
626 East North Central    16
Name: Division, dtype: int64
##################################################
627 East North Central    11
Name: Division, dtype: int64
##################################################
628 East North Central    10
Name: Division, dtype: int64
##################################################
629 East North Central    11
Name: Division, dtype: int64
##################################################
630 West North Central    24
Name: Division, dtype: int64
##################################################
631 West North Central    33
Name: Division, dtype: int64
##################################################
633 West North Central    10
Name: Division, dtype: int64
##################################################
634 West North Central    1
Name: Division, dtype: int64
##################################################
635 West North Central    1
Name: Division, dtype: int64
##################################################
636 West North Central    5
Name: Division, dtype: int64
##################################################
637 West North Central    2
Name: Division, dtype: int64
##################################################
638 West North Central    4
Name: Division, dtype: int64
##################################################
639 West North Central    5
Name: Division, dtype: int64
##################################################
640 West North Central    14
Name: Division, dtype: int64
##################################################
641 West North Central    18
Name: Division, dtype: int64
##################################################
646 West North Central    2
Name: Division, dtype: int64
##################################################
647 West North Central    2
Name: Division, dtype: int64
##################################################
648 West North Central    5
Name: Division, dtype: int64
##################################################
650 West North Central    2
Name: Division, dtype: int64
##################################################
651 West North Central    1
Name: Division, dtype: int64
##################################################
652 West North Central    5
Name: Division, dtype: int64
##################################################
654 West North Central    3
Name: Division, dtype: int64
##################################################
655 West North Central    2
Name: Division, dtype: int64
##################################################
656 West North Central    6
Name: Division, dtype: int64
##################################################
657 West North Central    8
Name: Division, dtype: int64
##################################################
658 West North Central    7
Name: Division, dtype: int64
##################################################
660 West North Central    12
Name: Division, dtype: int64
##################################################
661 West North Central    4
Name: Division, dtype: int64
##################################################
662 West North Central    6
Name: Division, dtype: int64
##################################################
664 West North Central    1
Name: Division, dtype: int64
##################################################
665 West North Central    2
Name: Division, dtype: int64
##################################################
666 West North Central    4
Name: Division, dtype: int64
##################################################
668 West North Central    1
Name: Division, dtype: int64
##################################################
670 West North Central    3
Name: Division, dtype: int64
##################################################
671 West North Central    2
Name: Division, dtype: int64
##################################################
672 West North Central    11
Name: Division, dtype: int64
##################################################
675 West North Central    2
Name: Division, dtype: int64
##################################################
678 West North Central    1
Name: Division, dtype: int64
##################################################
679 West North Central    1
Name: Division, dtype: int64
##################################################
680 West North Central    7
Name: Division, dtype: int64
##################################################
681 West North Central    15
Name: Division, dtype: int64
##################################################
684 West North Central    3
Name: Division, dtype: int64
##################################################
685 West North Central    3
Name: Division, dtype: int64
##################################################
686 West North Central    2
Name: Division, dtype: int64
##################################################
687 West North Central    2
Name: Division, dtype: int64
##################################################
688 West North Central    1
Name: Division, dtype: int64
##################################################
689 West North Central    3
Name: Division, dtype: int64
##################################################
691 West North Central    3
Name: Division, dtype: int64
##################################################
693 West North Central    1
Name: Division, dtype: int64
##################################################
700 West South Central    18
Name: Division, dtype: int64
##################################################
701 West South Central    25
Name: Division, dtype: int64
##################################################
703 West South Central    3
Name: Division, dtype: int64
##################################################
704 West South Central    16
Name: Division, dtype: int64
##################################################
705 West South Central    16
Name: Division, dtype: int64
##################################################
706 West South Central    10
Name: Division, dtype: int64
##################################################
707 West South Central    9
Name: Division, dtype: int64
##################################################
708 West South Central    6
Name: Division, dtype: int64
##################################################
710 West South Central    7
Name: Division, dtype: int64
##################################################
711 West South Central    9
Name: Division, dtype: int64
##################################################
712 West South Central    11
Name: Division, dtype: int64
##################################################
713 West South Central    4
Name: Division, dtype: int64
##################################################
714 West South Central    6
Name: Division, dtype: int64
##################################################
716 West South Central    4
Name: Division, dtype: int64
##################################################
718 West South Central    4
Name: Division, dtype: int64
##################################################
719 West South Central    5
Name: Division, dtype: int64
##################################################
720 West South Central    8
Name: Division, dtype: int64
##################################################
721 West South Central    6
Name: Division, dtype: int64
##################################################
722 East North Central    1
West South Central    3
Name: Division, dtype: int64
##################################################
723 West South Central    9
Name: Division, dtype: int64
##################################################
724 West South Central    1
Name: Division, dtype: int64
##################################################
725 West South Central    1
Name: Division, dtype: int64
##################################################
726 West South Central    3
Name: Division, dtype: int64
##################################################
727 West South Central    12
Name: Division, dtype: int64
##################################################
728 West South Central    2
Name: Division, dtype: int64
##################################################
729 Mountain              1
South Atlantic        1
West South Central    4
Name: Division, dtype: int64
##################################################
730 West South Central    20
Name: Division, dtype: int64
##################################################
731 West South Central    19
Name: Division, dtype: int64
##################################################
735 West South Central    2
Name: Division, dtype: int64
##################################################
737 West South Central    3
Name: Division, dtype: int64
##################################################
738 West South Central    1
Name: Division, dtype: int64
##################################################
740 West South Central    16
Name: Division, dtype: int64
##################################################
741 West South Central    8
Name: Division, dtype: int64
##################################################
743 West South Central    2
Name: Division, dtype: int64
##################################################
744 West South Central    7
Name: Division, dtype: int64
##################################################
745 West South Central    3
Name: Division, dtype: int64
##################################################
746 West South Central    2
Name: Division, dtype: int64
##################################################
747 West South Central    2
Name: Division, dtype: int64
##################################################
748 West South Central    5
Name: Division, dtype: int64
##################################################
749 West South Central    3
Name: Division, dtype: int64
##################################################
750 West South Central    96
Name: Division, dtype: int64
##################################################
751 West South Central    25
Name: Division, dtype: int64
##################################################
752 West South Central    47
Name: Division, dtype: int64
##################################################
754 West South Central    9
Name: Division, dtype: int64
##################################################
755 West South Central    6
Name: Division, dtype: int64
##################################################
756 West South Central    8
Name: Division, dtype: int64
##################################################
757 West South Central    12
Name: Division, dtype: int64
##################################################
758 West South Central    3
Name: Division, dtype: int64
##################################################
759 West South Central    11
Name: Division, dtype: int64
##################################################
760 West South Central    59
Name: Division, dtype: int64
##################################################
761 West South Central    38
Name: Division, dtype: int64
##################################################
762 West South Central    19
Name: Division, dtype: int64
##################################################
763 West South Central    9
Name: Division, dtype: int64
##################################################
764 West South Central    4
Name: Division, dtype: int64
##################################################
765 West South Central    11
Name: Division, dtype: int64
##################################################
766 West South Central    9
Name: Division, dtype: int64
##################################################
767 West South Central    5
Name: Division, dtype: int64
##################################################
768 West South Central    2
Name: Division, dtype: int64
##################################################
769 West South Central    7
Name: Division, dtype: int64
##################################################
770 Middle Atlantic         1
West South Central    131
Name: Division, dtype: int64
##################################################
772 West South Central    3
Name: Division, dtype: int64
##################################################
773 Middle Atlantic        1
West South Central    58
Name: Division, dtype: int64
##################################################
774 West South Central    53
Name: Division, dtype: int64
##################################################
775 West South Central    58
Name: Division, dtype: int64
##################################################
776 West South Central    11
Name: Division, dtype: int64
##################################################
777 West South Central    4
Name: Division, dtype: int64
##################################################
778 West South Central    19
Name: Division, dtype: int64
##################################################
779 West South Central    5
Name: Division, dtype: int64
##################################################
780 West South Central    22
Name: Division, dtype: int64
##################################################
781 West South Central    13
Name: Division, dtype: int64
##################################################
782 West South Central    72
Name: Division, dtype: int64
##################################################
783 West South Central    10
Name: Division, dtype: int64
##################################################
784 West South Central    17
Name: Division, dtype: int64
##################################################
785 West South Central    49
Name: Division, dtype: int64
##################################################
786 East South Central     1
West South Central    29
Name: Division, dtype: int64
##################################################
787 West South Central    41
Name: Division, dtype: int64
##################################################
788 West South Central    10
Name: Division, dtype: int64
##################################################
789 West South Central    4
Name: Division, dtype: int64
##################################################
790 West South Central    17
Name: Division, dtype: int64
##################################################
791 West South Central    20
Name: Division, dtype: int64
##################################################
792 West South Central    1
Name: Division, dtype: int64
##################################################
793 West South Central    15
Name: Division, dtype: int64
##################################################
794 West South Central    25
Name: Division, dtype: int64
##################################################
795 West South Central    2
Name: Division, dtype: int64
##################################################
796 West South Central    2
Name: Division, dtype: int64
##################################################
797 West South Central    19
Name: Division, dtype: int64
##################################################
798 West South Central    7
Name: Division, dtype: int64
##################################################
799 West South Central    40
Name: Division, dtype: int64
##################################################
800 New England     1
Mountain       63
Name: Division, dtype: int64
##################################################
801 Mountain    68
Name: Division, dtype: int64
##################################################
802 Mountain    78
Name: Division, dtype: int64
##################################################
803 Mountain    10
Name: Division, dtype: int64
##################################################
804 Mountain    22
Name: Division, dtype: int64
##################################################
805 Mountain    24
Name: Division, dtype: int64
##################################################
806 Mountain    10
Name: Division, dtype: int64
##################################################
807 Mountain    1
Name: Division, dtype: int64
##################################################
808 Mountain    10
Name: Division, dtype: int64
##################################################
809 South Atlantic     1
Mountain          30
Name: Division, dtype: int64
##################################################
810 Mountain    7
Name: Division, dtype: int64
##################################################
811 Mountain    5
Name: Division, dtype: int64
##################################################
812 Mountain    3
Name: Division, dtype: int64
##################################################
813 Mountain    3
Name: Division, dtype: int64
##################################################
814 Mountain    9
Name: Division, dtype: int64
##################################################
815 Mountain    13
Name: Division, dtype: int64
##################################################
816 Mountain    9
Name: Division, dtype: int64
##################################################
826 Mountain    2
Name: Division, dtype: int64
##################################################
827 Mountain    1
Name: Division, dtype: int64
##################################################
828 Mountain    1
Name: Division, dtype: int64
##################################################
832 Mountain    10
Name: Division, dtype: int64
##################################################
833 Mountain    10
Name: Division, dtype: int64
##################################################
834 Mountain    10
Name: Division, dtype: int64
##################################################
835 Mountain    1
Name: Division, dtype: int64
##################################################
836 Mountain    31
Name: Division, dtype: int64
##################################################
837 Mountain    18
Name: Division, dtype: int64
##################################################
838 Mountain    13
Name: Division, dtype: int64
##################################################
840 Mountain    12
Name: Division, dtype: int64
##################################################
841 Mountain    11
Name: Division, dtype: int64
##################################################
844 West South Central    1
Mountain              5
Name: Division, dtype: int64
##################################################
846 Mountain    3
Name: Division, dtype: int64
##################################################
847 Mountain    4
Name: Division, dtype: int64
##################################################
850 South Atlantic     1
Mountain          50
Name: Division, dtype: int64
##################################################
851 Mountain    10
Name: Division, dtype: int64
##################################################
852 West North Central     1
Mountain              57
Name: Division, dtype: int64
##################################################
853 Middle Atlantic        1
East North Central     1
Mountain              48
Name: Division, dtype: int64
##################################################
855 Mountain    2
Name: Division, dtype: int64
##################################################
856 Mountain    12
Name: Division, dtype: int64
##################################################
857 Mountain    38
Name: Division, dtype: int64
##################################################
859 Mountain    2
Name: Division, dtype: int64
##################################################
860 Mountain    1
Name: Division, dtype: int64
##################################################
863 Mountain    5
Name: Division, dtype: int64
##################################################
864 Mountain    1
Name: Division, dtype: int64
##################################################
870 Pacific      1
Mountain    17
Name: Division, dtype: int64
##################################################
871 Pacific                1
West South Central     2
Mountain              55
Name: Division, dtype: int64
##################################################
873 Mountain    3
Name: Division, dtype: int64
##################################################
874 Mountain    5
Name: Division, dtype: int64
##################################################
875 Mountain    24
Name: Division, dtype: int64
##################################################
877 Mountain    6
Name: Division, dtype: int64
##################################################
880 Mountain    13
Name: Division, dtype: int64
##################################################
881 Mountain    1
Name: Division, dtype: int64
##################################################
882 Mountain    11
Name: Division, dtype: int64
##################################################
883 West South Central    1
Mountain              5
Name: Division, dtype: int64
##################################################
890 Mountain    12
Name: Division, dtype: int64
##################################################
891 Mountain    30
Name: Division, dtype: int64
##################################################
894 Mountain    10
Name: Division, dtype: int64
##################################################
895 Mountain    7
Name: Division, dtype: int64
##################################################
897 Mountain    1
Name: Division, dtype: int64
##################################################
900 Mountain            1
South Atlantic      1
Pacific           235
Name: Division, dtype: int64
##################################################
902 South Atlantic      1
Pacific           114
Name: Division, dtype: int64
##################################################
903 Pacific    5
Name: Division, dtype: int64
##################################################
904 Pacific    5
Name: Division, dtype: int64
##################################################
905 Pacific    16
Name: Division, dtype: int64
##################################################
906 Pacific    72
Name: Division, dtype: int64
##################################################
907 Pacific    63
Name: Division, dtype: int64
##################################################
908 Pacific    36
Name: Division, dtype: int64
##################################################
910 Pacific    32
Name: Division, dtype: int64
##################################################
911 South Atlantic     1
Pacific           20
Name: Division, dtype: int64
##################################################
912 Pacific    30
Name: Division, dtype: int64
##################################################
913 Mountain            1
South Atlantic      2
Pacific           122
Name: Division, dtype: int64
##################################################
914 Pacific    23
Name: Division, dtype: int64
##################################################
915 Pacific    10
Name: Division, dtype: int64
##################################################
916 Pacific    17
Name: Division, dtype: int64
##################################################
917 Mountain      1
Pacific     169
Name: Division, dtype: int64
##################################################
918 Pacific    11
Name: Division, dtype: int64
##################################################
919 Pacific    25
Name: Division, dtype: int64
##################################################
920 Pacific    79
Name: Division, dtype: int64
##################################################
921 Pacific    49
Name: Division, dtype: int64
##################################################
922 Pacific    49
Name: Division, dtype: int64
##################################################
923 South Atlantic      1
Mountain            1
Pacific           101
Name: Division, dtype: int64
##################################################
924 Pacific    18
Name: Division, dtype: int64
##################################################
925 Pacific    86
Name: Division, dtype: int64
##################################################
926 Pacific    118
Name: Division, dtype: int64
##################################################
927 Middle Atlantic     1
Pacific            32
Name: Division, dtype: int64
##################################################
928 Mountain     2
Pacific     94
Name: Division, dtype: int64
##################################################
930 Pacific    34
Name: Division, dtype: int64
##################################################
931 Pacific    13
Name: Division, dtype: int64
##################################################
932 Pacific    38
Name: Division, dtype: int64
##################################################
933 Pacific    24
Name: Division, dtype: int64
##################################################
934 Pacific    31
Name: Division, dtype: int64
##################################################
935 Pacific    36
Name: Division, dtype: int64
##################################################
936 Pacific    36
Name: Division, dtype: int64
##################################################
937 Pacific    23
Name: Division, dtype: int64
##################################################
939 Pacific    27
Name: Division, dtype: int64
##################################################
940 Pacific    34
Name: Division, dtype: int64
##################################################
941 Pacific    37
Name: Division, dtype: int64
##################################################
943 Pacific    4
Name: Division, dtype: int64
##################################################
944 Pacific    3
Name: Division, dtype: int64
##################################################
945 West North Central     1
Pacific               67
Name: Division, dtype: int64
##################################################
946 Pacific    21
Name: Division, dtype: int64
##################################################
947 Pacific    9
Name: Division, dtype: int64
##################################################
948 Pacific    6
Name: Division, dtype: int64
##################################################
949 West South Central     1
Mountain               1
Pacific               19
Name: Division, dtype: int64
##################################################
950 Pacific    50
Name: Division, dtype: int64
##################################################
951 Pacific    29
Name: Division, dtype: int64
##################################################
952 Pacific    23
Name: Division, dtype: int64
##################################################
953 Pacific    49
Name: Division, dtype: int64
##################################################
954 Pacific    18
Name: Division, dtype: int64
##################################################
955 Pacific    13
Name: Division, dtype: int64
##################################################
956 Pacific    55
Name: Division, dtype: int64
##################################################
957 Pacific    11
Name: Division, dtype: int64
##################################################
958 Pacific    35
Name: Division, dtype: int64
##################################################
959 Pacific    41
Name: Division, dtype: int64
##################################################
960 Pacific    16
Name: Division, dtype: int64
##################################################
961 Pacific    5
Name: Division, dtype: int64
##################################################
967 Pacific    12
Name: Division, dtype: int64
##################################################
968 East South Central    1
Pacific               9
Name: Division, dtype: int64
##################################################
970 Mountain     1
Pacific     11
Name: Division, dtype: int64
##################################################
971 Pacific    9
Name: Division, dtype: int64
##################################################
972 Pacific    15
Name: Division, dtype: int64
##################################################
973 Pacific    12
Name: Division, dtype: int64
##################################################
974 Pacific    19
Name: Division, dtype: int64
##################################################
975 Pacific    12
Name: Division, dtype: int64
##################################################
976 Pacific    2
Name: Division, dtype: int64
##################################################
977 Pacific    1
Name: Division, dtype: int64
##################################################
978 Pacific    2
Name: Division, dtype: int64
##################################################
980 West South Central     1
Mountain               1
Pacific               46
Name: Division, dtype: int64
##################################################
981 Pacific    27
Name: Division, dtype: int64
##################################################
982 Pacific    27
Name: Division, dtype: int64
##################################################
983 Pacific    19
Name: Division, dtype: int64
##################################################
984 West South Central     1
Pacific               14
Name: Division, dtype: int64
##################################################
985 Pacific    5
Name: Division, dtype: int64
##################################################
986 Pacific    12
Name: Division, dtype: int64
##################################################
988 Pacific    10
Name: Division, dtype: int64
##################################################
989 Pacific    3
Name: Division, dtype: int64
##################################################
990 Pacific    7
Name: Division, dtype: int64
##################################################
991 East North Central    1
Pacific               8
Name: Division, dtype: int64
##################################################
992 Pacific    12
Name: Division, dtype: int64
##################################################
993 Pacific    6
Name: Division, dtype: int64
##################################################
994 Pacific    1
Name: Division, dtype: int64
##################################################
995 Pacific    2
Name: Division, dtype: int64
##################################################
996 Pacific    2
Name: Division, dtype: int64
##################################################
998 Pacific    1
Name: Division, dtype: int64
##################################################
999 Pacific    1
Name: Division, dtype: int64
In [43]:
test["Division"] = test.apply(lambda row: stocker_Region.get(row["patient_zip3"], row["Division"]), axis=1)
In [44]:
train = train.drop(train[train['age_under_10'].isna()].index) 
In [45]:
list_inpute = list()
for col in train.columns : 
    if train.isna().sum().loc[col] > 0 and col !='bmi' and col !="payer_type":
        list_inpute.append(col)
In [46]:
im = dict()
list_inpute = list_inpute  # Replace with your actual column names

# Filter out rows where 'patient_state' is not "TX"
filtered_data = train[train['patient_state'] == "TX"]

for col in list_inpute:
    # Check if there are any missing values
    if filtered_data[col].isnull().any():
        # If there are missing values, fill them with 0
        filtered_data[col].fillna(0, inplace=True)

    # Exclude non-numeric values before calculating the median
    numeric_values = pd.to_numeric(filtered_data[col], errors='coerce')  # Coerce non-numeric values to NaN
    numeric_values = numeric_values.dropna()  # Drop NaN values
    if not numeric_values.empty:
        # Calculate the median for the specified column and store it in the dictionary
        im[col] = numeric_values.median()
In [47]:
# im = dict()

# for col in list_inpute:
#     # Filter out rows where 'patient_state' is not "TX"
#     filtered_data = train[train['patient_state'] == "TX"]
    
#     # Fill missing values in the specified column with 0
#     filtered_data[col].fillna(0, inplace=True)
    
#     # Calculate the median for the specified column and store in the dictionary
#     im[col] = np.median(filtered_data[col])

# # Now 'im' contains the median values for each specified column
In [48]:
for col in im:
    train.loc[train['patient_state'] == "TX", col] = train.loc[train['patient_state'] == "TX", col].apply(lambda x: im[col] if pd.isna(x) else x)
    test.loc[test['patient_state'] == "TX", col] = test.loc[test['patient_state'] == "TX", col].apply(lambda x: im[col] if pd.isna(x) else x)
In [49]:
# AllData = pd.DataFrame()
# for col in test.columns : 
#     L1 = list(train[col].values)
#     L2 = list(test[col].values)
#     L = L1 +L2
#     AllData[col] = L
In [50]:
# k = set()
# L = list()
# for zipcode in AllData.patient_state.unique() : 
#     a = AllData[AllData['patient_state'] == zipcode].Division.nunique()
#     if a>1 : 
#         L.append(zipcode)
#     k.add(a)
    
# print(k)
In [51]:
# for i in AllData.patient_state.unique() :
#     print( i ,AllData [AllData['patient_state'] == i].Division.unique() )
In [52]:
# def update_diagnosis2(row):
#     for i in L : 
#         if row["patient_state"] == i:

#             row["Division"] = train[train['patient_state'] == i].Division.unique()[0]
#     return row

# test = test.apply(update_diagnosis2, axis=1)
In [53]:
categorical_cols = train.select_dtypes(include=['object', 'category']).columns
numerical_cols = train.select_dtypes(include=['float64', 'int64']).columns

# Impute categorical columns using mode
for col in categorical_cols:
    if col != 'DiagPeriodL90D':
        mode = train[col].mode()[0]
        train[col].fillna(mode, inplace=True)
        test[col].fillna(mode, inplace=True)
In [54]:
fill_air = dict()
fill_air['Ozone'] = np.median(train[(train['Region']=="West") & (train['Division']=="Pacific")& (~train['Ozone'].isna())]['Ozone'])
fill_air['PM25'] = np.median(train[(train['Region']=="West") & (train['Division']=="Pacific")& (~train['Ozone'].isna())]['PM25'])
fill_air['N02'] = np.median(train[(train['Region']=="West") & (train['Division']=="Pacific")& (~train['Ozone'].isna())]['N02'])
In [55]:
for i in fill_air : 
    train[i].fillna(fill_air[i] , inplace= True)
    test[i].fillna(fill_air[i] , inplace= True)
In [56]:
class Stock : 
    n,_ = train.shape
    y = train.DiagPeriodL90D
    n_splits =10
    folds = StratifiedKFold(n_splits = n_splits)
In [57]:
AllData = pd.DataFrame()
for col in test.columns : 
    L1 = list(train[col].values)
    L2 = list(test[col].values)
    L = L1 +L2
    AllData[col] = L
used_impute = AllData[AllData['bmi'].notna()]
used_impute2 = AllData[AllData['bmi'].isna()]
In [58]:
from catboost import CatBoostRegressor
model = CatBoostRegressor(random_seed=42 , cat_features = [i for i in train.columns if train[i].dtype == 'object']).fit(used_impute.drop('bmi' , axis=1) , used_impute.bmi)
used_impute2['bmi'] = model.predict(used_impute2.drop('bmi' , axis=1))
Learning rate set to 0.053929
0:	learn: 5.6607300	total: 175ms	remaining: 2m 54s
1:	learn: 5.6529937	total: 209ms	remaining: 1m 44s
2:	learn: 5.6463393	total: 247ms	remaining: 1m 21s
3:	learn: 5.6393584	total: 290ms	remaining: 1m 12s
4:	learn: 5.6332012	total: 327ms	remaining: 1m 5s
5:	learn: 5.6260057	total: 372ms	remaining: 1m 1s
6:	learn: 5.6207643	total: 414ms	remaining: 58.7s
7:	learn: 5.6186142	total: 456ms	remaining: 56.6s
8:	learn: 5.6128234	total: 495ms	remaining: 54.5s
9:	learn: 5.6096213	total: 539ms	remaining: 53.4s
10:	learn: 5.6048702	total: 578ms	remaining: 51.9s
11:	learn: 5.6013497	total: 615ms	remaining: 50.6s
12:	learn: 5.5978292	total: 653ms	remaining: 49.6s
13:	learn: 5.5914440	total: 691ms	remaining: 48.7s
14:	learn: 5.5876448	total: 731ms	remaining: 48s
15:	learn: 5.5831133	total: 778ms	remaining: 47.8s
16:	learn: 5.5795695	total: 814ms	remaining: 47.1s
17:	learn: 5.5749190	total: 850ms	remaining: 46.4s
18:	learn: 5.5728040	total: 876ms	remaining: 45.2s
19:	learn: 5.5683862	total: 913ms	remaining: 44.8s
20:	learn: 5.5656511	total: 957ms	remaining: 44.6s
21:	learn: 5.5622403	total: 1000ms	remaining: 44.4s
22:	learn: 5.5596084	total: 1.06s	remaining: 44.9s
23:	learn: 5.5569622	total: 1.09s	remaining: 44.5s
24:	learn: 5.5537708	total: 1.13s	remaining: 44.1s
25:	learn: 5.5503866	total: 1.18s	remaining: 44s
26:	learn: 5.5458503	total: 1.22s	remaining: 43.8s
27:	learn: 5.5432079	total: 1.25s	remaining: 43.6s
28:	learn: 5.5402057	total: 1.3s	remaining: 43.5s
29:	learn: 5.5371516	total: 1.34s	remaining: 43.2s
30:	learn: 5.5335361	total: 1.38s	remaining: 43s
31:	learn: 5.5303663	total: 1.43s	remaining: 43.2s
32:	learn: 5.5283801	total: 1.47s	remaining: 43.1s
33:	learn: 5.5270242	total: 1.51s	remaining: 42.9s
34:	learn: 5.5232985	total: 1.55s	remaining: 42.9s
35:	learn: 5.5220798	total: 1.62s	remaining: 43.4s
36:	learn: 5.5211088	total: 1.68s	remaining: 43.6s
37:	learn: 5.5193862	total: 1.72s	remaining: 43.5s
38:	learn: 5.5172351	total: 1.76s	remaining: 43.5s
39:	learn: 5.5148758	total: 1.8s	remaining: 43.3s
40:	learn: 5.5127477	total: 1.85s	remaining: 43.2s
41:	learn: 5.5106728	total: 1.89s	remaining: 43s
42:	learn: 5.5092079	total: 1.93s	remaining: 42.8s
43:	learn: 5.5061774	total: 1.97s	remaining: 42.7s
44:	learn: 5.5036465	total: 2s	remaining: 42.5s
45:	learn: 5.5021310	total: 2.04s	remaining: 42.3s
46:	learn: 5.5000071	total: 2.08s	remaining: 42.2s
47:	learn: 5.4991447	total: 2.12s	remaining: 42s
48:	learn: 5.4965876	total: 2.15s	remaining: 41.8s
49:	learn: 5.4950554	total: 2.19s	remaining: 41.6s
50:	learn: 5.4925773	total: 2.23s	remaining: 41.6s
51:	learn: 5.4906844	total: 2.34s	remaining: 42.6s
52:	learn: 5.4873545	total: 2.38s	remaining: 42.5s
53:	learn: 5.4838298	total: 2.42s	remaining: 42.4s
54:	learn: 5.4822988	total: 2.46s	remaining: 42.2s
55:	learn: 5.4811297	total: 2.5s	remaining: 42.2s
56:	learn: 5.4794341	total: 2.54s	remaining: 42s
57:	learn: 5.4761682	total: 2.6s	remaining: 42.2s
58:	learn: 5.4746618	total: 2.66s	remaining: 42.4s
59:	learn: 5.4732760	total: 2.7s	remaining: 42.3s
60:	learn: 5.4698964	total: 2.74s	remaining: 42.2s
61:	learn: 5.4662523	total: 2.79s	remaining: 42.2s
62:	learn: 5.4630836	total: 2.83s	remaining: 42.1s
63:	learn: 5.4608913	total: 2.86s	remaining: 41.9s
64:	learn: 5.4596910	total: 2.91s	remaining: 41.8s
65:	learn: 5.4578927	total: 2.94s	remaining: 41.7s
66:	learn: 5.4571492	total: 2.98s	remaining: 41.5s
67:	learn: 5.4568616	total: 3.03s	remaining: 41.5s
68:	learn: 5.4568114	total: 3.04s	remaining: 41s
69:	learn: 5.4550796	total: 3.08s	remaining: 40.9s
70:	learn: 5.4532224	total: 3.12s	remaining: 40.8s
71:	learn: 5.4532200	total: 3.14s	remaining: 40.5s
72:	learn: 5.4520050	total: 3.18s	remaining: 40.4s
73:	learn: 5.4517568	total: 3.22s	remaining: 40.3s
74:	learn: 5.4501645	total: 3.25s	remaining: 40.1s
75:	learn: 5.4475121	total: 3.29s	remaining: 40.1s
76:	learn: 5.4450558	total: 3.33s	remaining: 39.9s
77:	learn: 5.4436345	total: 3.37s	remaining: 39.8s
78:	learn: 5.4428886	total: 3.41s	remaining: 39.8s
79:	learn: 5.4410312	total: 3.45s	remaining: 39.7s
80:	learn: 5.4394233	total: 3.49s	remaining: 39.6s
81:	learn: 5.4384322	total: 3.53s	remaining: 39.5s
82:	learn: 5.4362393	total: 3.57s	remaining: 39.4s
83:	learn: 5.4352272	total: 3.61s	remaining: 39.4s
84:	learn: 5.4337127	total: 3.66s	remaining: 39.4s
85:	learn: 5.4317192	total: 3.7s	remaining: 39.4s
86:	learn: 5.4316904	total: 3.76s	remaining: 39.5s
87:	learn: 5.4302821	total: 3.83s	remaining: 39.7s
88:	learn: 5.4291684	total: 3.87s	remaining: 39.6s
89:	learn: 5.4266312	total: 3.91s	remaining: 39.5s
90:	learn: 5.4252213	total: 3.95s	remaining: 39.5s
91:	learn: 5.4235889	total: 3.98s	remaining: 39.3s
92:	learn: 5.4226997	total: 4.02s	remaining: 39.2s
93:	learn: 5.4225899	total: 4.06s	remaining: 39.1s
94:	learn: 5.4189801	total: 4.11s	remaining: 39.1s
95:	learn: 5.4172950	total: 4.15s	remaining: 39.1s
96:	learn: 5.4160139	total: 4.2s	remaining: 39.1s
97:	learn: 5.4152024	total: 4.24s	remaining: 39s
98:	learn: 5.4140367	total: 4.28s	remaining: 39s
99:	learn: 5.4121202	total: 4.33s	remaining: 39s
100:	learn: 5.4113374	total: 4.37s	remaining: 38.9s
101:	learn: 5.4087029	total: 4.42s	remaining: 38.9s
102:	learn: 5.4082752	total: 4.46s	remaining: 38.8s
103:	learn: 5.4068088	total: 4.49s	remaining: 38.7s
104:	learn: 5.4041276	total: 4.53s	remaining: 38.6s
105:	learn: 5.4032251	total: 4.57s	remaining: 38.5s
106:	learn: 5.4022184	total: 4.61s	remaining: 38.4s
107:	learn: 5.3990197	total: 4.64s	remaining: 38.4s
108:	learn: 5.3984685	total: 4.68s	remaining: 38.3s
109:	learn: 5.3940296	total: 4.73s	remaining: 38.3s
110:	learn: 5.3907674	total: 4.77s	remaining: 38.2s
111:	learn: 5.3902129	total: 4.82s	remaining: 38.2s
112:	learn: 5.3896302	total: 4.86s	remaining: 38.2s
113:	learn: 5.3886535	total: 4.91s	remaining: 38.2s
114:	learn: 5.3873368	total: 4.96s	remaining: 38.1s
115:	learn: 5.3864268	total: 5.01s	remaining: 38.2s
116:	learn: 5.3852905	total: 5.06s	remaining: 38.2s
117:	learn: 5.3822413	total: 5.1s	remaining: 38.2s
118:	learn: 5.3801330	total: 5.14s	remaining: 38.1s
119:	learn: 5.3791878	total: 5.18s	remaining: 38s
120:	learn: 5.3788299	total: 5.22s	remaining: 37.9s
121:	learn: 5.3785357	total: 5.26s	remaining: 37.8s
122:	learn: 5.3758404	total: 5.3s	remaining: 37.8s
123:	learn: 5.3738218	total: 5.35s	remaining: 37.8s
124:	learn: 5.3725618	total: 5.39s	remaining: 37.8s
125:	learn: 5.3706913	total: 5.44s	remaining: 37.8s
126:	learn: 5.3673451	total: 5.5s	remaining: 37.8s
127:	learn: 5.3659090	total: 5.54s	remaining: 37.8s
128:	learn: 5.3639542	total: 5.58s	remaining: 37.7s
129:	learn: 5.3623587	total: 5.63s	remaining: 37.7s
130:	learn: 5.3614131	total: 5.67s	remaining: 37.6s
131:	learn: 5.3604579	total: 5.73s	remaining: 37.7s
132:	learn: 5.3600344	total: 5.77s	remaining: 37.6s
133:	learn: 5.3599861	total: 5.79s	remaining: 37.5s
134:	learn: 5.3577621	total: 5.84s	remaining: 37.4s
135:	learn: 5.3564945	total: 5.91s	remaining: 37.5s
136:	learn: 5.3548712	total: 5.97s	remaining: 37.6s
137:	learn: 5.3518939	total: 6.02s	remaining: 37.6s
138:	learn: 5.3506199	total: 6.06s	remaining: 37.6s
139:	learn: 5.3478941	total: 6.11s	remaining: 37.5s
140:	learn: 5.3475503	total: 6.15s	remaining: 37.5s
141:	learn: 5.3463191	total: 6.18s	remaining: 37.4s
142:	learn: 5.3436463	total: 6.22s	remaining: 37.3s
KeyboardInterrupt

In [ ]:
AllData_copy = AllData.copy()

# Replace missing values in 'bmi' column with values from 'used_impute'
AllData_copy['bmi'] = AllData_copy['bmi'].combine_first(used_impute['bmi'])

# Replace non-missing values in 'bmi' column with values from 'used_impute2'
AllData_copy['bmi'] = AllData_copy['bmi'].combine_first(used_impute2['bmi'])
In [ ]:
train = AllData_copy[:train.shape[0]]
test = AllData_copy[train.shape[0]:]
In [ ]:
train['patient_race'] = train_patient_race
test['patient_race'] = test_patient_race
In [ ]:
used_impute2
In [ ]:
AllData = pd.DataFrame()
for col in test.columns : 
    L1 = list(train[col].values)
    L2 = list(test[col].values)
    L = L1 +L2
    AllData[col] = L
used_impute = AllData[AllData['patient_race'].notna()]
used_impute2 = AllData[AllData['patient_race'].isna()]

from catboost import CatBoostClassifier
model = CatBoostClassifier(random_seed=42 , cat_features = [i for i in train.columns if (train[i].dtype == 'object' and i!='patient_race') ]).fit(used_impute.drop('patient_race' , axis=1) , used_impute.patient_race)
In [ ]:
used_impute2['patient_race'] = model.predict(used_impute2.drop('patient_race' , axis=1)).squeeze()
In [ ]:
AllData_copy = AllData.copy()

# Replace missing values in 'bmi' column with values from 'used_impute'
AllData_copy['patient_race'] = AllData_copy['patient_race'].combine_first(used_impute['patient_race'])

# Replace non-missing values in 'bmi' column with values from 'used_impute2'
AllData_copy['patient_race'] = AllData_copy['patient_race'].combine_first(used_impute2['patient_race'])


train = AllData_copy[:train.shape[0]]
test = AllData_copy[train.shape[0]:]
In [ ]:
train['DiagPeriodL90D'] = Stock.y.values
In [ ]:
train['Age_diff_mean'] = train['patient_age'] - train['age_median']
train['Area'] = train['population']/train['density']


test['Age_diff_mean'] = test['patient_age'] - test['age_median']
test['Area'] = test['population']/test['density']



train['ratio'] = train['bmi']/train['patient_age']
test['ratio'] = test['bmi']/test['patient_age']

train['product'] = train['bmi']*train['patient_age']
test['product'] = test['bmi']*test['patient_age']
In [ ]:
train.drop('patient_id' , axis=1 , inplace = True)
test.drop('patient_id' , axis=1 , inplace = True)
In [ ]:
train['extract2']  = train['breast_cancer_diagnosis_code'].apply(lambda x :x[:5])
train['extract3']  = train['breast_cancer_diagnosis_code'].apply(lambda x :x[:6])


test['extract2']  = test['breast_cancer_diagnosis_code'].apply(lambda x :x[:5])
test['extract3']  = test['breast_cancer_diagnosis_code'].apply(lambda x :x[:6])
In [ ]:
column_types = train.dtypes

# Step 2: Filter out numeric columns excluding binary ones
numeric_features = column_types[column_types != 'object']  # Exclude non-numeric columns
binary_features = [col for col in numeric_features.index if train[col].nunique() == 2]  # Identify binary columns
non_binary_numeric_features = numeric_features.drop(binary_features).index.tolist()  # Exclude binary columns

# Step 3: Extract non-binary numeric features from train
train_numeric = train[non_binary_numeric_features]

# Display the extracted numerical features DataFrame
print(train_numeric)
In [ ]:
pure_num_features = train_numeric.columns
In [ ]:
pure_num_features
In [ ]:
# for col in pure_num_features : 
#     if col != "income_qcut":
#         print("#"*50)
#         print(col)
#         print("#"*50)
#         for i in range(3,7) : 

#             train['income_qcut'] = pd.qcut(train[col], q=i)
#             a = pd.crosstab(train['income_qcut' ], [train[ 'DiagPeriodL90D']])
#             a['0p'] = a[0] *100/(a[0] +a[1]) # u can obeserve the trend even for 0 if u observe it on Op
#             a['1p'] = a[1] *100/(a[0] +a[1])
#             plt.plot(np.arange(len(a)), a['0p'], marker='o')
#             plt.xlabel('Bins of income_qcut')
#             plt.ylabel('Percentage of 0 occurrences')
#             plt.title('Trend of 0 occurrences across income_qcut')
#             plt.xticks(np.arange(len(a)), a.index)
#             plt.show()

#             # Displaying the DataFrame
#             print(a)
#     else : 
#         continue
In [ ]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

bin_columns = {}


for col in pure_num_features:
    b=0
    if col != "income_qcut":
        print("#" * 50)
        print(col)
        print("#" * 50)
        for i in range(6, 2 , -1):
            train['income_qcut'] = pd.qcut(train[col], q=i)
            a = pd.crosstab(train['income_qcut'], [train['DiagPeriodL90D']])
            a['0p'] = a[0] * 100 / (a[0] + a[1])
            a['1p'] = a[1] * 100 / (a[0] + a[1])
            plt.plot(np.arange(len(a)), a['0p'], marker='o')
            plt.xlabel('Bins of income_qcut')
            plt.ylabel('Percentage of 0 occurrences')
            plt.title('Trend of 0 occurrences across income_qcut')
            plt.xticks(np.arange(len(a)), a.index)
            plt.show()

            trend = np.diff(a['0p'])
            if all(trend > 0):
                trend_direction = "strictly positive"
            elif all(trend < 0):
                trend_direction = "strictly negative"
            else:
                trend_direction = "mixed"
            
            if trend_direction in ['strictly positive', 'strictly negative']  :
                if  b==0:
                    print("Column:", col)
                    print("Number of bins:", i)
                    print("Trend direction:", trend_direction)
                    print()
                    bin_columns[f'{col}_{i}'] = i
                    train[f'{col}_{i}'] = pd.qcut(train[col], q=i, labels=False, duplicates='drop')
                    test[f'{col}_{i}'] = pd.qcut(test[col], q=i, labels=False, duplicates='drop')
                    b +=1
            print(a)
    else:
        continue
In [ ]:
pure_num_features
In [ ]:
# from collections import defaultdict
# def majority_payer_ind (df, co11, co12):
#     g1= df.groupby ([col1]).agg({co12:lambda x: pd.Series.mode(x)})
#     g1= g1 [co12].to_dict()
#     print(g1)
#     def ind_map(x):
#         try:
#             return 1 if x[co12] == g1[x[col]] else 0
#         except:
#             return np.nan

#     df['Maj_'+co12+'_'+co11+'_ind'] = df.apply(lambda x: ind_map(x), axis=1)
# for col1 in [ 'patient_zip3', 'Division', 'Region']:
#     for co12 in ['payer_type', 'patient_state', 'breast_cancer_diagnosis_code', 'metastatic_cancer_diagnosis_code']:
#         majority_payer_ind(train,col1, co12)
#         majority_payer_ind (test, col1, co12)
In [ ]:
# from collections import defaultdict
# import pandas as pd
# import numpy as np

# def majority_payer_ind(df, col1, col2):
#     g1 = df.groupby([col1]).agg({col2: lambda x: x.mode().tolist()})
#     g1 = g1[col2].to_dict()

#     def ind_map(x):
#         try:
#             return 1 if x[col2] in g1[x[col1]] else 0
#         except:
#             return np.nan

#     df['Maj_' + col2 + '_' + col1 + '_ind'] = df.apply(lambda x: ind_map(x), axis=1)



# for col1 in ["patient_race" , 'patient_zip3', 'Division', 'Region']:
#     for col2 in ['payer_type', 'patient_state', 'breast_cancer_diagnosis_code', 'metastatic_cancer_diagnosis_code']:
#         majority_payer_ind(train, col1, col2)
#         majority_payer_ind(test, col1, col2)
In [ ]:
train.head()
In [ ]:
# AllData = pd.DataFrame()
# for col in test.columns : 
#     L1 = list(train[col].values)
#     L2 = list(test[col].values)
#     L = L1 +L2
#     AllData[col] = L
In [ ]:
# cols_to_agg = ["bmi" ,"patient_age" ,"age_median"]
# group_by_cols =["payer_type" , "patient_zip3" ,"patient_state" , "breast_cancer_diagnosis_code" ,"breast_cancer_diagnosis_desc" , 
#                "Region" , "Division" , "AgeCat" , "metastatic_cancer_diagnosis_code" ,"patient_state" ,"combinaison_codes"]
# aggregation_strategies = ["min" , "max"  , "mean" ,"median"]
In [ ]:
# #daoud

# for col_to_agg in cols_to_agg:
#     for col in group_by_cols:
#         for strategy in aggregation_strategies:
#             AllData[f'{col_to_agg} {strategy} by {col}'] = AllData.groupby(col)[col_to_agg].transform(strategy)

# AllData.drop(group_by_cols,axis=1,inplace=True)
In [ ]:
# train = AllData_copy[:train.shape[0]]
# test = AllData_copy[train.shape[0]:]

# train['DiagPeriodL90D'] = Stock.y.values
In [ ]:
bin_columns
In [ ]:
train.head()
In [ ]:
check_nan(train)
In [ ]:
train.shape
In [ ]:
class Stock : 
    n,_ = train.shape
    y = train.DiagPeriodL90D
    n_splits =5
    folds = StratifiedKFold(n_splits = n_splits)
In [ ]:
def correct_metastatic_codes(df) : 
    df['metastatic_cancer_diagnosis_code'] = df['metastatic_cancer_diagnosis_code'].apply(lambda x : x[:3]+'.'+x[3:])
    return df

train = correct_metastatic_codes(train)
test = correct_metastatic_codes(test)
In [ ]:
# C79.1 Secondary malignant neoplasm of bladder and other and unspecified urinary organs #general
    
# #plus specifique
#         C79.10 Secondary malignant neoplasm of unspecified urinary organs 
#         C79.11 Secondary malignant neoplasm of bladder
#         C79.19 Secondary malignant neoplasm of other urinary organs
In [ ]:
# C79.5 Secondary malignant neoplasm of bone and bone marrow #general
    
# #plus specifique
#          C79.51 Secondary malignant neoplasm of bone
#          C79.52 Secondary malignant neoplasm of bone marrow
In [ ]:
#  C79.3 Secondary malignant neoplasm of brain and cerebral meninges #general 
# #plus specifique
#      C79.31 Secondary malignant neoplasm of brain
#      C79.32 Secondary malignant neoplasm of cerebral meninges
In [ ]:
# # shih 3andha el cancer fel breast fel blasa eli hkina 3leha m loul ama entecher lahne zeda
# "C79.89"  : "Secondary malignant neoplasm of other specified sites"
# "C77.3" : "Secondary and unspecified malignant neoplasm of axilla and upper limb lymph nodes"
# "C79.81" : "Secondary malignant neoplasm of breast" 
# "C77.9" : "Secondary and unspecified malignant neoplasm of lymph node, unspecified"
# "C78.0-" : "Secondary malignant neoplasm of lung"
# "C79.9" : "Secondary malignant neoplasm of unspecified site"
# "C78.1" : "Secondary malignant neoplasm of mediastinum"
# "C79.5_" : "Secondary malignant neoplasm of bone and bone marrow"
# "C79.2" : "Secondary malignant neoplasm of skin"
# "C78.7" : "Secondary malignant neoplasm of liver and intrahepatic bile duct"
# "C77.1" : "Secondary and unspecified malignant neoplasm of intrathoracic lymph nodes"
# "C79.3_" : "Secondary malignant neoplasm of brain cerebral meninges"
# "C79.82" : "Secondary malignant neoplasm of genital organs"
# "C77.0" : "Secondary and unspecified malignant neoplasm of lymph nodes of head, face and neck"
# "C78.2" : "Secondary malignant neoplasm of pleura"
# "C78.6" : "Secondary malignant neoplasm of retroperitoneum and peritoneum"
# "C79.4-" : "Secondary malignant neoplasm of other and unspecified parts of nervous system"
# "C78.8-" : "Secondary malignant neoplasm of other and unspecified digestive organs"
# "C78.0-" : "Secondary malignant neoplasm of lung"
# "C78.5" : "Secondary malignant neoplasm of large intestine and rectum"
# "C77.8" : "Secondary and unspecified malignant neoplasm of lymph nodes of multiple regions"
# "C78.4" : "Secondary malignant neoplasm of small intestine"
# "C79.6-" : "Secondary malignant neoplasm of ovary"
# "C77.2" : "Secondary and unspecified malignant neoplasm of intraabdominal lymph nodes"
# "C79.3-" : "Secondary malignant neoplasm of brain cerebral meninges"
# "C79.7-" : "Secondary malignant neoplasm of adrenal gland"
# "C77.4" : "Secondary and unspecified malignant neoplasm of inguinal and lower limb lymph nodes"
# "C79.1-" : "Secondary malignant neoplasm of bladder and other urinary organs"
# "C79.0-" : "Secondary malignant neoplasm of kidney and renal pelvis"
# "C77.5" : "Secondary and unspecified malignant neoplasm of intrapelvic lymph nodes"
# "C78.3-" : "Secondary malignant neoplasm of other and unspecified respiratory organs"
In [ ]:
# # extrat code 1
# C77  Secondary and unspecified malignant neoplasm of lymph nodes
# C78  Secondary malignant neoplasm of respiratory and digestive organs
# C79  Secondary malignant neoplasm of other and unspecified sites

# # extrat code 2
In [ ]:
train.metastatic_cancer_diagnosis_code.unique()
In [ ]:
train[train['metastatic_cancer_diagnosis_code']=='C79.61'].breast_cancer_diagnosis_desc.unique()
In [ ]:
train['extract_metastatic1'] = train['metastatic_cancer_diagnosis_code'].apply(lambda x :x[:3])
# train['extract_metastatic2']  = train['metastatic_cancer_diagnosis_code'].apply(lambda x :x[:5])



test['extract_metastatic1'] = test['metastatic_cancer_diagnosis_code'].apply(lambda x :x[:3])
# test['extract_metastatic2']  = test['metastatic_cancer_diagnosis_code'].apply(lambda x :x[:5])
In [ ]:
train['combinaison_codes'] = train["breast_cancer_diagnosis_code"].astype(str) + '_' + train["metastatic_cancer_diagnosis_code"].astype(str)
test['combinaison_codes'] = test["breast_cancer_diagnosis_code"].astype(str) + '_' + test["metastatic_cancer_diagnosis_code"].astype(str)
In [ ]:
train['AgeCat'] = np.round(train.patient_age/20).astype(np.uint16).astype('str')
test['AgeCat'] = np.round(test.patient_age/20).astype(np.uint16).astype('str')
In [ ]:
min(train.unemployment_rate.unique())
In [ ]:
train['patient_zip3'] = train['patient_zip3'].astype("category")
test['patient_zip3'] = test['patient_zip3'].astype("category")
In [ ]:
train['new_conbin'] = train['combinaison_codes']+"_"+train['patient_race']
test['new_conbin'] = test['combinaison_codes']+"_"+test['patient_race']
In [ ]:
train['new_conbin2'] = train['combinaison_codes']+"_"+train['AgeCat']
test['new_conbin2'] = test['combinaison_codes']+"_"+test['AgeCat']
In [ ]:
train['Allconbin'] = train['combinaison_codes']+"_"+train['AgeCat']+train['patient_race']+ train['patient_state']
test['Allconbin'] = test['combinaison_codes']+"_"+test['AgeCat']+test['patient_race']+ test['patient_state']
In [ ]:
# def transform_age(df) : 
#     bins = [0, 9, 19, 29, 39, 49, 59, 69, 79, float('inf')]
#     labels = ['age_un_10', 'age_10_2_19', 'age_20', 'age_30', 'age_40', 'age_50', 'age_60', 'age_70', 'age_ov_80']

#     df['age_group'] = pd.cut(df['patient_age'], bins=bins, labels=labels, right=False)

#     df_age_features = pd.get_dummies(df['age_group']).astype(int)

#     df = pd.concat([df, df_age_features], axis=1)

#     df = df.drop('age_group', axis=1)

#     return df


# train = transform_age(train)
# test = transform_age(test)
In [ ]:
def combinations(df) : 
#     df['combination2'] = df['extract2']+'_'+df['extract_metastatic2']
    df['combination1'] = df['extract2']+'_'+df['extract_metastatic1']
    df['combination8'] = df['extract2']+'_'+df['metastatic_cancer_diagnosis_code']
#     df['combination3'] = df['extract3']+'_'+df['extract_metastatic2']
    df['combination4'] = df['extract3']+'_'+df['extract_metastatic1']
    df['combination9'] = df['extract3']+'_'+df['metastatic_cancer_diagnosis_code']
    df['combination6'] = df['breast_cancer_diagnosis_code']+'_'+df['extract_metastatic1']
#     df['combination7'] = df['breast_cancer_diagnosis_code']+'_'+df['extract_metastatic2']
    df['Safe_Neighborhood'] = df['Crime_Rate'].apply(lambda x: 1 if x in ['well below average', 'slightly below average'] else 0)

    return df

train = combinations(train)
test = combinations(test)
In [ ]:
def New_FE(df) : 
# #     to_mul_div = to_mul_div = [
# #     "widowed", "family_dual_income","married", "never_married", "divorced", "health_uninsured"
# # ]

# #     for col in to_mul_div : 
# #         df[f'{col}_TV'] = (df[col]*df['population'])/100
#     df['mamlouka'] = df['housing_units']*(df['home_ownership']/100)
#     df['mekreya'] = df['housing_units']-df['mamlouka']
    df['9asem'] = df['income_household_median']/df['family_size']
    df['fadhel'] = df['income_household_median']-df['rent_median']
#     df['fadhel_9asem'] = (df['income_household_median']-df['rent_median'])/df['family_size']
    df['idk'] = (df['income_household_median']-df['income_individual_median'])/df['family_size']
    df["HHI"] = df['rent_median']/df['rent_burden']
    df["retirement"] = (df["patient_age"]>=65).astype(int)
    
# #     df['custom_feature'] = (
# #     (df['ICD10'] == 1) &
# #     (df['payer_type'] == 'MEDICARE ADVANTAGE') &
# #     (df['retirement'] == 1) &
# #     (df['patient_state'].isin(['MS', 'ID', 'UT', 'AR', 'NV', 'MO', 'HI', 'TN', 'IA', 'LA', 'SC', 'VA']))).astype(int)
# #     df['immune'] = (df['patient_age']<23).astype(int)
# #     df['mostly_have_disability'] = ((df['payer_type'] == "MEDICARE ADVANTAGE") & (df['patient_age'] < 65)).astype(int).values
# #     df['low_income'] = (df['payer_type'] == "MEDICAID").astype(int).values
    
    return df
In [ ]:
# train.drop(['mamlouka','mekreya','9asem','fadhel','fadhel_9asem','idk',"HHI","retirement"],axis=1,inplace =True)
# test.drop(['mamlouka','mekreya','9asem','fadhel','fadhel_9asem','idk',"HHI","retirement"],axis=1,inplace =True)
In [ ]:
# df['mostly_have_disability'] = df[(df['payer_type'] =="MEDICARE ADVANTAGE")&(df['patient_age'] <65)]
# df['low_income'] = (df['payer_type'] == "MEDICAID").astype(int)
In [ ]:
train = New_FE(train)
test = New_FE(test)
In [ ]:
train.head()
In [ ]:
def add_neighbors(train) : 
# Create the neighbors dictionary
    neighbors_dict = {
        'CA': ['OR', 'NV', 'AZ'],
        'TX': ['NM', 'OK', 'AR', 'LA'],
        'ID': ['WA', 'OR', 'MT', 'WY', 'UT', 'NV'],
        'NY': ['VT', 'MA', 'CT', 'NJ', 'PA'],
        'IL': ['WI', 'IA', 'MO', 'KY', 'IN'],
        'MI': ['WI', 'IN', 'OH'],
        'OR': ['WA', 'ID', 'CA', 'NV'],
        'MT': ['ID', 'WY', 'SD', 'ND'],
        'KY': ['IL', 'IN', 'OH', 'WV', 'VA', 'TN', 'MO'],
        'OH': ['MI', 'IN', 'KY', 'WV', 'PA'],
        'IN': ['MI', 'IL', 'KY', 'OH'],
        'FL': ['GA', 'AL'],
        'CO': ['WY', 'NE', 'KS', 'OK', 'NM', 'UT'],
        'GA': ['FL', 'AL', 'TN', 'NC', 'SC'],
        'VA': ['MD', 'WV', 'KY', 'NC', 'TN'],
        'MD': ['PA', 'WV', 'VA', 'DE', 'DC'],
        'KS': ['NE', 'MO', 'OK', 'CO'],
        'WI': ['MI', 'IL', 'IA', 'MN'],
        'PA': ['NY', 'NJ', 'DE', 'MD', 'WV', 'OH'],
        'NM': ['AZ', 'UT', 'CO', 'OK', 'TX'],
        'WA': ['OR', 'ID'],
        'MN': ['ND', 'SD', 'IA', 'WI'],
        'NC': ['VA', 'TN', 'GA', 'SC'],
        'AL': ['FL', 'GA', 'TN', 'MS'],
        'SC': ['NC', 'GA'],
        'LA': ['TX', 'AR', 'MS'],
        'IA': ['MN', 'WI', 'IL', 'MO', 'NE', 'SD'],
        'TN': ['KY', 'VA', 'NC', 'GA', 'AL', 'MS', 'AR', 'MO'],
        'HI': [],  # Hawaii doesn't share land borders with other states
        'NE': ['SD', 'IA', 'MO', 'KS', 'CO', 'WY'],
        'AZ': ['CA', 'NV', 'UT', 'CO', 'NM'],
        'MO': ['IA', 'IL', 'KY', 'TN', 'AR', 'OK', 'KS', 'NE'],
        'NV': ['OR', 'ID', 'UT', 'AZ', 'CA'],
        'SD': ['ND', 'MN', 'IA', 'NE', 'WY', 'MT'],
        'DC': ['MD', 'VA'],
        'AR': ['MO', 'TN', 'MS', 'LA', 'OK', 'TX'],
        'UT': ['ID', 'WY', 'CO', 'NM', 'AZ', 'NV'],
        'WV': ['OH', 'PA', 'MD', 'VA', 'KY'],
        'ND': ['MN', 'SD', 'MT'],
        'OK': ['KS', 'MO', 'AR', 'TX', 'CO', 'NM'],
        'WY': ['MT', 'ID', 'UT', 'CO', 'NE', 'SD'],
        'DE': ['PA', 'MD', 'NJ'],
        'NJ': ['NY', 'PA', 'DE'],
        'MS': ['TN', 'AR', 'LA', 'AL'],
        'AK': [],  # Alaska is not included in this list as it's not part of the contiguous states
        'PR': [],  # Puerto Rico is not part of the contiguous states
        'RI': ['MA', 'CT'],
        'CT': ['MA', 'RI', 'NY'],
        'NH': ['VT', 'ME', 'MA'],
        'MA': ['NH', 'VT', 'RI', 'CT', 'NY'],
    }

    # Function to check if a state is a neighbor
    def is_neighbor(row, neighbor_list):
        return row in neighbor_list

    # Add columns for each state indicating whether it is a neighbor or not
    for state in neighbors_dict.keys():
        train[f'{state}_neighbor'] = train['patient_state'].apply(lambda x: is_neighbor(x, neighbors_dict[state]))

    # Replace True/False with 1/0 if needed
    train.replace({True: 1, False: 0}, inplace=True)

    for state in ["AK" , "PR" , "RI" , "NH" ,"HI"] :
        train.drop([f'{state}_neighbor'], axis=1 , inplace =True)
    
    return train


train = add_neighbors(train)
test = add_neighbors(test)
In [ ]:
    neighbors_dict = {
        'CA': ['OR', 'NV', 'AZ'],
        'TX': ['NM', 'OK', 'AR', 'LA'],
        'ID': ['WA', 'OR', 'MT', 'WY', 'UT', 'NV'],
        'NY': ['VT', 'MA', 'CT', 'NJ', 'PA'],
        'IL': ['WI', 'IA', 'MO', 'KY', 'IN'],
        'MI': ['WI', 'IN', 'OH'],
        'OR': ['WA', 'ID', 'CA', 'NV'],
        'MT': ['ID', 'WY', 'SD', 'ND'],
        'KY': ['IL', 'IN', 'OH', 'WV', 'VA', 'TN', 'MO'],
        'OH': ['MI', 'IN', 'KY', 'WV', 'PA'],
        'IN': ['MI', 'IL', 'KY', 'OH'],
        'FL': ['GA', 'AL'],
        'CO': ['WY', 'NE', 'KS', 'OK', 'NM', 'UT'],
        'GA': ['FL', 'AL', 'TN', 'NC', 'SC'],
        'VA': ['MD', 'WV', 'KY', 'NC', 'TN'],
        'MD': ['PA', 'WV', 'VA', 'DE', 'DC'],
        'KS': ['NE', 'MO', 'OK', 'CO'],
        'WI': ['MI', 'IL', 'IA', 'MN'],
        'PA': ['NY', 'NJ', 'DE', 'MD', 'WV', 'OH'],
        'NM': ['AZ', 'UT', 'CO', 'OK', 'TX'],
        'WA': ['OR', 'ID'],
        'MN': ['ND', 'SD', 'IA', 'WI'],
        'NC': ['VA', 'TN', 'GA', 'SC'],
        'AL': ['FL', 'GA', 'TN', 'MS'],
        'SC': ['NC', 'GA'],
        'LA': ['TX', 'AR', 'MS'],
        'IA': ['MN', 'WI', 'IL', 'MO', 'NE', 'SD'],
        'TN': ['KY', 'VA', 'NC', 'GA', 'AL', 'MS', 'AR', 'MO'],
        'HI': [],  # Hawaii doesn't share land borders with other states
        'NE': ['SD', 'IA', 'MO', 'KS', 'CO', 'WY'],
        'AZ': ['CA', 'NV', 'UT', 'CO', 'NM'],
        'MO': ['IA', 'IL', 'KY', 'TN', 'AR', 'OK', 'KS', 'NE'],
        'NV': ['OR', 'ID', 'UT', 'AZ', 'CA'],
        'SD': ['ND', 'MN', 'IA', 'NE', 'WY', 'MT'],
        'DC': ['MD', 'VA'],
        'AR': ['MO', 'TN', 'MS', 'LA', 'OK', 'TX'],
        'UT': ['ID', 'WY', 'CO', 'NM', 'AZ', 'NV'],
        'WV': ['OH', 'PA', 'MD', 'VA', 'KY'],
        'ND': ['MN', 'SD', 'MT'],
        'OK': ['KS', 'MO', 'AR', 'TX', 'CO', 'NM'],
        'WY': ['MT', 'ID', 'UT', 'CO', 'NE', 'SD'],
        'DE': ['PA', 'MD', 'NJ'],
        'NJ': ['NY', 'PA', 'DE'],
        'MS': ['TN', 'AR', 'LA', 'AL'],
        'AK': [],  # Alaska is not included in this list as it's not part of the contiguous states
        'PR': [],  # Puerto Rico is not part of the contiguous states
        'RI': ['MA', 'CT'],
        'CT': ['MA', 'RI', 'NY'],
        'NH': ['VT', 'ME', 'MA'],
        'MA': ['NH', 'VT', 'RI', 'CT', 'NY'],
    }
In [ ]:
def has_water_border(state, neighbors_dict):
    # List of states with coastlines
    states_with_water = ['CA', 'TX', 'FL', 'NY', 'OR', 'WA', 'HI', 'AK', 'PR']

    # Check if the state has any coastal neighbors
    coastal_neighbors = any(neigh in states_with_water for neigh in neighbors_dict.get(state, []))

    return coastal_neighbors

# Add a new column 'has_water_border' to the DataFrame
train['has_water_border'] = train['patient_state'].apply(lambda x: has_water_border(x, neighbors_dict))

# Replace True/False with 1/0 if needed
train.replace({True: 1, False: 0}, inplace=True)



test['has_water_border'] = test['patient_state'].apply(lambda x: has_water_border(x, neighbors_dict))

# Replace True/False with 1/0 if needed
test.replace({True: 1, False: 0}, inplace=True)
In [ ]:
check_nan(test)
In [ ]:
check_nan(train)
In [ ]:
#######################################################""
In [ ]:
 
In [ ]:
 
In [ ]:
##################################################
In [ ]:
train.metastatic_cancer_diagnosis_code.unique()
In [ ]:
train.drop('has_water_border' ,axis=1 , inplace=True)
test.drop('has_water_border' ,axis=1 , inplace=True)
In [ ]:
train_copy = train.copy(deep = True)
test_copy = test.copy(deep = True)
In [ ]:
correlation_matrix = train.select_dtypes(include = ['number']).corr()
features_with_corr_1 = correlation_matrix[correlation_matrix.isin([1.0, -1.0]) & (correlation_matrix != 1.0)].stack().index
features_with_corr_1
In [ ]:
# train_copy2 = train.drop('extract_metastatic1' ,axis=1 )
# test_copy2 = test.drop('extract_metastatic1' ,axis=1 )
In [ ]:
train_copy['new_feature'] = train_copy['ICD10'].astype(str)+"_"+train_copy['income_household_six_figure'].astype(str)
test_copy['new_feature'] = test_copy['ICD10'].astype(str)+"_"+test_copy['income_household_six_figure'].astype(str)
In [ ]:
train_copy44 = train_copy.copy(deep  = True)
In [ ]:
train_copy.rename(columns=to_map_columns, inplace=True)
test_copy.rename(columns=to_map_columns, inplace=True)
In [ ]:
 
In [ ]:
to_map_columns = {'new_feature': 'ICD10_income_household_six_figure',
 'new_feature2': 'ICD10_MO_neighbor',
 'new_feature3': 'ICD10_ID_neighbor',
 'new_feature4': 'ICD10_race_black',
 'new_feature5': 'ICD10_VA_neighbor',
 'new_feature6': 'ICD10_patient_race',
 'new_feature7': 'ICD10_AgeCat',
 'new_feature8': 'ICD10_income_household_under_5_3',
 'new_feature9': 'ICD10_education_some_college_4',
 'new_feature10': 'ICD10_ age_70s',
 'new_feature11': 'ICD10_density',
 'new_feature12': 'ICD10_Place',
 'new_feature13': 'ICD10_metastatic_cancer_diagnosis_code',
 'new_feature14': 'ICD10_age_10_to_19',
 'new_feature15': 'ICD10_CT_neighbor',
 'new_feature16': 'ICD10_male_1',
 'new_feature17': 'ICD10_combination8',
 'new_feature18': 'ICD10_limited_english',
 'new_feature19': 'ICD10_age_30s',
 'new_feature20': 'ICD10_age_10_to_19_3',
 'new_feature21': 'ICD10_veteran',
 'new_feature22': 'ICD10_rent_burden',
 'new_feature23': 'ICD10_age_40s',
 'new_feature24': 'ICD10_income_household_35_to_50_5',
 'new_feature25': 'ICD10_income_household_20_to_25_3',
 'new_feature26': 'ICD10_race_white',
 'new_feature27': 'ICD10_race_other',
 'new_feature28': 'ICD10_disabled',
 'new_feature29': 'ICD10_age_50s',
 'new_feature30': 'ICD10_education_graduate_3',
 'new_feature31': 'ICD10_poverty',
 'new_feature32': 'ICD10_Left',
 'new_feature33': 'ICD10_combination4',
 'new_feature34': 'ICD10_education_less_highschool',
 'new_feature35': 'ICD10_housing_units',
 'new_feature36': 'ICD10_race_pacific',
 'new_feature37': 'ICD10_education_highschool',
 'new_feature38': 'ICD10_income_individual_median',
 'new_feature39': 'ICD10_income_household_50_to_75',
 'new_feature40': 'ICD10_education_stem_degree',
 'new_feature41': 'ICD10_divorced',
 'new_feature42': 'ICD10_AR_neighbor',
 'new_feature43': 'ICD10_labor_force_participation_4',
 'new_feature44': 'ICD10_breast_cancer_diagnosis_desc',
 'new_feature45': 'ICD10_income_household_75_to_100_5',
 'new_feature46': 'ICD10_health_uninsured',
 'new_feature47': 'ICD10_farmer',
 'new_feature48': 'ICD10_female_1',
 'new_feature49': 'ICD10_patient_age_income_household_six_figure_4',
 'new_feature50': 'ICD10_patient_age_age_30s_3',
 'new_feature51': 'ICD10_patient_age_NV_neighbor',
 'new_feature52': 'ICD10_patient_age_payer_type',
 'new_feature53': 'ICD10_patient_age_health_uninsured',
 'new_feature54': 'ICD10_combination1_payer_type',
 'new_feature55': 'ICD10_male_patient_UT_neighbor',
 'new_feature56': 'ICD10_Left_combination4',
 'new_feature57': 'ICD10_breast_cancer_diagnosis_desc_income_household_25_to_35_4',
 'new_feature58': 'ICD10_patient_age_patient_race',
 'new_feature59': 'ICD10_metastatic_cancer_diagnosis_code_Division',
 'new_feature60': 'ICD10_patient_age_widowed_4'}
In [ ]:
train_copy['new_feature2'] = train_copy['ICD10'].astype(str)+"_"+train_copy['MO_neighbor'].astype(str)
test_copy['new_feature2'] =test_copy['ICD10'].astype(str)+"_"+test_copy['MO_neighbor'].astype(str)
In [ ]:
train_copy['new_feature3'] = train_copy['ICD10'].astype(str)+"_"+train_copy['ID_neighbor'].astype(str)
test_copy['new_feature3'] = test_copy['ICD10'].astype(str)+"_"+test_copy['ID_neighbor'].astype(str)
In [ ]:
def drop_column(df , col) : 
    df.drop(col , axis=1 , inplace =True)
    return df
In [ ]:
# train_copy = drop_column(train_copy,'education_some_college_4')
# test_copy = drop_column(test_copy,'education_some_college_4')
In [ ]:
train_copy['new_feature4'] = train_copy['ICD10'].astype(str)+"_"+train_copy['race_black'].astype(str)
test_copy['new_feature4'] = test_copy['ICD10'].astype(str)+"_"+test_copy['race_black'].astype(str)
In [ ]:
train_copy['new_feature5'] = train_copy['ICD10'].astype(str)+"_"+train_copy['VA_neighbor'].astype(str)
test_copy['new_feature5'] = test_copy['ICD10'].astype(str)+"_"+test_copy['VA_neighbor'].astype(str)
In [ ]:
train_copy['new_feature6'] = train_copy['ICD10'].astype(str)+"_"+train_copy['patient_race'].astype(str)
test_copy['new_feature6'] = test_copy['ICD10'].astype(str)+"_"+test_copy['patient_race'].astype(str)
In [ ]:
train_copy['new_feature7'] = train_copy['ICD10'].astype(str)+"_"+train_copy['AgeCat'].astype(str)
test_copy['new_feature7'] = test_copy['ICD10'].astype(str)+"_"+test_copy['AgeCat'].astype(str)
In [ ]:
train_copy['new_feature8'] = train_copy['ICD10'].astype(str)+"_"+train_copy['income_household_under_5_3'].astype(str)
test_copy['new_feature8'] = test_copy['ICD10'].astype(str)+"_"+test_copy['income_household_under_5_3'].astype(str)
In [ ]:
train_copy['new_feature9'] = train_copy['ICD10'].astype(str)+"_"+train_copy['education_some_college_4'].astype(str)
test_copy['new_feature9'] = test_copy['ICD10'].astype(str)+"_"+test_copy['education_some_college_4'].astype(str)
In [ ]:
 
In [ ]:
from sklearn.cluster import KMeans


train_copy['new_feature10'] = train_copy['ICD10'].astype(str)+"_"+train_copy['age_70s'].astype(str)
test_copy['new_feature10'] = test_copy['ICD10'].astype(str)+"_"+test_copy['age_70s'].astype(str)
# combined_feature = 'new_feature10'  # Replace with your actual combined column name

# # Extract unique values from the combined column and encode them numerically
# encoded_values = pd.factorize(train_copy[combined_feature])[0].reshape(-1, 1)
# encoded_values2 = pd.factorize(test_copy[combined_feature])[0].reshape(-1, 1)
# # Apply KMeans clustering
# kmeans = KMeans(n_clusters=1000, random_state=42)  # Choose the number of clusters
# train_copy['cluster_label'] = kmeans.fit_predict(encoded_values)
# test_copy['cluster_label'] = kmeans.fit_predict(encoded_values2)

# train_copy.drop('new_feature10' ,axis=1 , inplace =True)
# test_copy.drop('new_feature10' ,axis=1 , inplace =True)
In [ ]:
train_copy['new_feature11'] = train_copy['ICD10'].astype(str)+"_"+train_copy['density'].astype(str)
test_copy['new_feature11'] = test_copy['ICD10'].astype(str)+"_"+test_copy['density'].astype(str)
In [ ]:
train_copy['new_feature12'] = train_copy['ICD10'].astype(str)+"_"+train_copy['Place'].astype(str)
test_copy['new_feature12'] = test_copy['ICD10'].astype(str)+"_"+test_copy['Place'].astype(str)
In [ ]:
train_copy['new_feature13'] = train_copy['ICD10'].astype(str)+"_"+train_copy['metastatic_cancer_diagnosis_code'].astype(str)
test_copy['new_feature13'] = test_copy['ICD10'].astype(str)+"_"+test_copy['metastatic_cancer_diagnosis_code'].astype(str)

# combined_feature = 'new_feature13'  # Replace with your actual combined column name

# # Extract unique values from the combined column and encode them numerically
# encoded_values = pd.factorize(train_copy[combined_feature])[0].reshape(-1, 1)
# encoded_values2 = pd.factorize(test_copy[combined_feature])[0].reshape(-1, 1)
# # Apply KMeans clustering
# kmeans = KMeans(n_clusters=40, random_state=42)  # Choose the number of clusters
# train_copy['cluster_label'] = kmeans.fit_predict(encoded_values)
# test_copy['cluster_label'] = kmeans.fit_predict(encoded_values2)

# train_copy.drop('new_feature13' ,axis=1 , inplace =True)
# test_copy.drop('new_feature13' ,axis=1 , inplace =True)
In [ ]:
 
In [ ]:
 
In [ ]:
train_copy['new_feature14'] = train_copy['ICD10'].astype(str)+"_"+train_copy['age_10_to_19'].astype(str)
test_copy['new_feature14'] = test_copy['ICD10'].astype(str)+"_"+test_copy['age_10_to_19'].astype(str)
In [ ]:
train_copy['new_feature15'] = train_copy['ICD10'].astype(str)+"_"+train_copy['CT_neighbor'].astype(str)
test_copy['new_feature15'] = test_copy['ICD10'].astype(str)+"_"+test_copy['CT_neighbor'].astype(str) # maybe remove
In [ ]:
train_copy['new_feature16'] = train_copy['ICD10'].astype(str)+"_"+train_copy['male_1'].astype(str)
test_copy['new_feature16'] = test_copy['ICD10'].astype(str)+"_"+test_copy['male_1'].astype(str) 
In [ ]:
train_copy['new_feature17'] = train_copy['ICD10'].astype(str)+"_"+train_copy['combination8'].astype(str)
test_copy['new_feature17'] = test_copy['ICD10'].astype(str)+"_"+test_copy['combination8'].astype(str)
In [ ]:
train_copy['new_feature18'] = train_copy['ICD10'].astype(str)+"_"+train_copy['limited_english'].astype(str)
test_copy['new_feature18'] = test_copy['ICD10'].astype(str)+"_"+test_copy['limited_english'].astype(str)
In [ ]:
train_copy['new_feature19'] = train_copy['ICD10'].astype(str)+"_"+train_copy['age_30s'].astype(str)
test_copy['new_feature19'] = test_copy['ICD10'].astype(str)+"_"+test_copy['age_30s'].astype(str)
In [ ]:
train_copy['new_feature20'] = train_copy['ICD10'].astype(str)+"_"+train_copy['age_10_to_19_3'].astype(str)
test_copy['new_feature20'] = test_copy['ICD10'].astype(str)+"_"+test_copy['age_10_to_19_3'].astype(str)
In [ ]:
train_copy['new_feature21'] = train_copy['ICD10'].astype(str)+"_"+train_copy['veteran'].astype(str)
test_copy['new_feature21'] = test_copy['ICD10'].astype(str)+"_"+test_copy['veteran'].astype(str)
In [ ]:
train_copy['new_feature22'] = train_copy['ICD10'].astype(str)+"_"+train_copy['rent_burden'].astype(str)
test_copy['new_feature22'] = test_copy['ICD10'].astype(str)+"_"+test_copy['rent_burden'].astype(str)
In [ ]:
train_copy['new_feature23'] = train_copy['ICD10'].astype(str)+"_"+train_copy['age_40s'].astype(str)
test_copy['new_feature23'] = test_copy['ICD10'].astype(str)+"_"+test_copy['age_40s'].astype(str)
In [ ]:
train_copy['new_feature24'] = train_copy['ICD10'].astype(str)+"_"+train_copy['income_household_35_to_50_5'].astype(str)
test_copy['new_feature24'] = test_copy['ICD10'].astype(str)+"_"+test_copy['income_household_35_to_50_5'].astype(str)
In [ ]:
train_copy['new_feature25'] = train_copy['ICD10'].astype(str)+"_"+train_copy['income_household_20_to_25_3'].astype(str)
test_copy['new_feature25'] = test_copy['ICD10'].astype(str)+"_"+test_copy['income_household_20_to_25_3'].astype(str)
In [ ]:
train_copy['new_feature26'] = train_copy['ICD10'].astype(str)+"_"+train_copy['race_white'].astype(str)
test_copy['new_feature26'] = test_copy['ICD10'].astype(str)+"_"+test_copy['race_white'].astype(str)
In [ ]:
train_copy['new_feature27'] = train_copy['ICD10'].astype(str)+"_"+train_copy['race_other'].astype(str)
test_copy['new_feature27'] = test_copy['ICD10'].astype(str)+"_"+test_copy['race_other'].astype(str)
In [ ]:
train_copy['new_feature28'] = train_copy['ICD10'].astype(str)+"_"+train_copy['disabled'].astype(str)
test_copy['new_feature28'] = test_copy['ICD10'].astype(str)+"_"+test_copy['disabled'].astype(str)
In [ ]:
train_copy['new_feature29'] = train_copy['ICD10'].astype(str)+"_"+train_copy['age_50s'].astype(str)
test_copy['new_feature29'] = test_copy['ICD10'].astype(str)+"_"+test_copy['age_50s'].astype(str)
In [ ]:
train_copy['new_feature30'] = train_copy['ICD10'].astype(str)+"_"+train_copy['education_graduate_3'].astype(str)
test_copy['new_feature30'] = test_copy['ICD10'].astype(str)+"_"+test_copy['education_graduate_3'].astype(str)
In [ ]:
train_copy['new_feature31'] = train_copy['ICD10'].astype(str)+"_"+train_copy['poverty'].astype(str)
test_copy['new_feature31'] = test_copy['ICD10'].astype(str)+"_"+test_copy['poverty'].astype(str)
In [ ]:
train_copy['new_feature32'] = train_copy['ICD10'].astype(str)+"_"+train_copy['Left'].astype(str)
test_copy['new_feature32'] = test_copy['ICD10'].astype(str)+"_"+test_copy['Left'].astype(str)
In [ ]:
train_copy['new_feature33'] = train_copy['ICD10'].astype(str)+"_"+train_copy['combination4'].astype(str)
test_copy['new_feature33'] = test_copy['ICD10'].astype(str)+"_"+test_copy['combination4'].astype(str)
In [ ]:
 
In [ ]:
train_copy['new_feature34'] = train_copy['ICD10'].astype(str)+"_"+train_copy['education_less_highschool'].astype(str)
test_copy['new_feature34'] = test_copy['ICD10'].astype(str)+"_"+test_copy['education_less_highschool'].astype(str)
In [ ]:
train_copy['new_feature35'] = train_copy['ICD10'].astype(str)+"_"+train_copy['housing_units'].astype(str)
test_copy['new_feature35'] = test_copy['ICD10'].astype(str)+"_"+test_copy['housing_units'].astype(str)
In [ ]:
train_copy['new_feature36'] = train_copy['ICD10'].astype(str)+"_"+train_copy['race_pacific'].astype(str)
test_copy['new_feature36'] = test_copy['ICD10'].astype(str)+"_"+test_copy['race_pacific'].astype(str)
In [ ]:
train_copy['new_feature37'] = train_copy['ICD10'].astype(str)+"_"+train_copy['education_highschool'].astype(str)
test_copy['new_feature37'] = test_copy['ICD10'].astype(str)+"_"+test_copy['education_highschool'].astype(str)
In [ ]:
train_copy['new_feature38'] = train_copy['ICD10'].astype(str)+"_"+train_copy['income_individual_median'].astype(str)
test_copy['new_feature38'] = test_copy['ICD10'].astype(str)+"_"+test_copy['income_individual_median'].astype(str)
In [ ]:
train_copy['new_feature39'] = train_copy['ICD10'].astype(str)+"_"+train_copy['income_household_50_to_75'].astype(str)
test_copy['new_feature39'] = test_copy['ICD10'].astype(str)+"_"+test_copy['income_household_50_to_75'].astype(str)
In [ ]:
train_copy['new_feature40'] = train_copy['ICD10'].astype(str)+"_"+train_copy['education_stem_degree'].astype(str)
test_copy['new_feature40'] = test_copy['ICD10'].astype(str)+"_"+test_copy['education_stem_degree'].astype(str)
In [ ]:
train_copy['new_feature41'] = train_copy['ICD10'].astype(str)+"_"+train_copy['divorced'].astype(str)
test_copy['new_feature41'] = test_copy['ICD10'].astype(str)+"_"+test_copy['divorced'].astype(str)
In [ ]:
train_copy['new_feature42'] = train_copy['ICD10'].astype(str)+"_"+train_copy['AR_neighbor'].astype(str)
test_copy['new_feature42'] = test_copy['ICD10'].astype(str)+"_"+test_copy['AR_neighbor'].astype(str)
In [ ]:
train_copy['new_feature43'] = train_copy['ICD10'].astype(str)+"_"+train_copy['labor_force_participation_4'].astype(str)
test_copy['new_feature43'] = test_copy['ICD10'].astype(str)+"_"+test_copy['labor_force_participation_4'].astype(str)
In [ ]:
train_copy['new_feature44'] = train_copy['ICD10'].astype(str)+"_"+train_copy['breast_cancer_diagnosis_desc'].astype(str)
test_copy['new_feature44'] = test_copy['ICD10'].astype(str)+"_"+test_copy['breast_cancer_diagnosis_desc'].astype(str)
In [ ]:
 
In [ ]:
train_copy['new_feature45'] = train_copy['ICD10'].astype(str)+"_"+train_copy['income_household_75_to_100_5'].astype(str)
test_copy['new_feature45'] = test_copy['ICD10'].astype(str)+"_"+test_copy['income_household_75_to_100_5'].astype(str)
In [ ]:
train_copy['new_feature46'] = train_copy['ICD10'].astype(str)+"_"+train_copy['health_uninsured'].astype(str)
test_copy['new_feature46'] = test_copy['ICD10'].astype(str)+"_"+test_copy['health_uninsured'].astype(str)
In [ ]:
train_copy['new_feature47'] = train_copy['ICD10'].astype(str)+"_"+train_copy['farmer'].astype(str)
test_copy['new_feature47'] = test_copy['ICD10'].astype(str)+"_"+test_copy['farmer'].astype(str) # try to take 6 number after , 
In [ ]:
train_copy['new_feature48'] = train_copy['ICD10'].astype(str)+"_"+train_copy['female_1'].astype(str)
test_copy['new_feature48'] = test_copy['ICD10'].astype(str)+"_"+test_copy['female_1'].astype(str)
In [ ]:
train_copy['new_feature49'] = train_copy['ICD10'].astype(str)+"_"+train_copy['patient_age'].astype(str)+"_"+train_copy['income_household_six_figure_4'].astype(str)
test_copy['new_feature49'] = test_copy['ICD10'].astype(str)+"_"+test_copy['patient_age'].astype(str)+"_"+test_copy['income_household_six_figure_4'].astype(str)
In [ ]:
# new_feature49 = {['0_22_0', '0_26_0', '1_18_0', '1_18_1', '1_18_2', '1_18_3', '1_19_0',
#        '1_19_1', '1_19_2', '1_19_3', '1_20_2', '1_20_3', '1_21_1', '1_21_3',
#        '1_22_1', '1_22_2', '1_22_3', '1_23_1', '1_23_2', '1_23_3', '1_24_0',
#        '1_24_2', '1_25_0', '1_25_3', '1_26_0', '1_26_2', '1_26_3', '1_30_1',
#        '1_78_2', '1_79_2'] : '0' , 
#                 ['0_23_1', '0_24_0', '0_24_2', '0_25_1', '0_25_2', '0_25_3', '0_27_1',
#        '0_27_2', '0_27_3', '0_28_2', '0_29_0', '0_29_1', '0_29_2', '0_30_1',
#        '0_30_3', '0_31_0', '0_31_1', '0_32_0', '0_32_1', '0_33_0', '0_33_1',
#        '0_33_2', '0_33_3', '0_34_0', '0_34_3', '0_35_1', '0_35_2', '0_36_0',
#        '0_36_1', '0_36_2', '0_36_3', '0_37_0', '0_37_2', '0_37_3', '0_38_0',
#        '0_38_1', '0_39_0', '0_39_1', '0_39_3', '0_40_1', '0_40_2', '0_40_3',
#        '0_41_1', '0_41_2', '0_41_3', '0_42_0', '0_42_3', '0_43_0', '0_43_1',
#        '0_43_3', '0_44_1', '0_44_3', '0_45_1', '0_47_1', '0_49_0', '0_49_2',
#        '0_51_2', '0_52_2', '0_53_0', '0_53_2', '0_53_3', '0_64_0', '0_67_1',
#        '0_68_0', '0_68_1', '0_68_3', '0_70_0', '0_70_3', '0_71_1', '0_71_3',
#        '0_72_1', '0_72_2', '0_73_0', '0_73_3', '0_74_2', '0_74_3', '0_75_1',
#        '0_75_3', '0_76_0', '0_84_3', '1_90_3'] : '1'}

# train_copy['new_feature49'] = train_copy['new_feature49'].apply()

new_feature49_mapping = {
    tuple(['0_22_0', '0_26_0', '1_18_0', '1_18_1', '1_18_2', '1_18_3', '1_19_0', '1_19_1', '1_19_2', '1_19_3', '1_20_2', '1_20_3', '1_21_1', '1_21_3', '1_22_1', '1_22_2', '1_22_3', '1_23_1', '1_23_2', '1_23_3', '1_24_0', '1_24_2', '1_25_0', '1_25_3', '1_26_0', '1_26_2', '1_26_3', '1_30_1', '1_78_2', '1_79_2']): '0',
    tuple(['0_23_1', '0_24_0', '0_24_2', '0_25_1', '0_25_2', '0_25_3', '0_27_1', '0_27_2', '0_27_3', '0_28_2', '0_29_0', '0_29_1', '0_29_2', '0_30_1', '0_30_3', '0_31_0', '0_31_1', '0_32_0', '0_32_1', '0_33_0', '0_33_1', '0_33_2', '0_33_3', '0_34_0', '0_34_3', '0_35_1', '0_35_2', '0_36_0', '0_36_1', '0_36_2', '0_36_3', '0_37_0', '0_37_2', '0_37_3', '0_38_0', '0_38_1', '0_39_0', '0_39_1', '0_39_3', '0_40_1', '0_40_2', '0_40_3', '0_41_1', '0_41_2', '0_41_3', '0_42_0', '0_42_3', '0_43_0', '0_43_1', '0_43_3', '0_44_1', '0_44_3', '0_45_1', '0_47_1', '0_49_0', '0_49_2', '0_51_2', '0_52_2', '0_53_0', '0_53_2', '0_53_3', '0_64_0', '0_67_1', '0_68_0', '0_68_1', '0_68_3', '0_70_0', '0_70_3', '0_71_1', '0_71_3', '0_72_1', '0_72_2', '0_73_0', '0_73_3', '0_74_2', '0_74_3', '0_75_1', '0_75_3', '0_76_0', '0_84_3', '1_90_3']): '1'
}

# Apply the mapping to the 'new_feature49' column
train_copy['new_feature49'] = train_copy['new_feature49'].map(lambda x: new_feature49_mapping[tuple(x)] if tuple(x) in new_feature49_mapping else x)
test_copy['new_feature49'] = test_copy['new_feature49'].map(lambda x: new_feature49_mapping[tuple(x)] if tuple(x) in new_feature49_mapping else x)
In [ ]:
 
In [ ]:
train_copy['new_feature50'] = train_copy['ICD10'].astype(str)+"_"+train_copy['patient_age'].astype(str)+"_"+train_copy['age_30s_3'].astype(str)
test_copy['new_feature50'] = test_copy['ICD10'].astype(str)+"_"+test_copy['patient_age'].astype(str)+"_"+test_copy['age_30s_3'].astype(str)
In [ ]:
train_copy['new_feature51'] = train_copy['ICD10'].astype(str)+"_"+train_copy['patient_age'].astype(str)+"_"+train_copy['NV_neighbor'].astype(str)
test_copy['new_feature51'] = test_copy['ICD10'].astype(str)+"_"+test_copy['patient_age'].astype(str)+"_"+test_copy['NV_neighbor'].astype(str)
In [ ]:
train_copy = drop_column(train_copy,'new_feature51')
test_copy = drop_column(test_copy,'new_feature51')
In [ ]:
train_copy.head()
In [ ]:
train_copy['new_feature52'] = train_copy['ICD10'].astype(str)+"_"+train_copy['patient_age'].astype(str)+"_"+train_copy['payer_type'].astype(str)
test_copy['new_feature52'] = test_copy['ICD10'].astype(str)+"_"+test_copy['patient_age'].astype(str)+"_"+test_copy['payer_type'].astype(str)
In [ ]:
new_columns = ['ICD10_income_household_six_figure', 'ICD10_MO_neighbor', 'ICD10_ID_neighbor' ,'ICD10_race_black' ,
               "ICD10_VA_neighbor" , "ICD10_patient_race" ,"ICD10_AgeCat" ,"ICD10_income_household_under_5_3",
               "ICD10_education_some_college_4","ICD10_ age_70s" ,"ICD10_density" ,"ICD10_Place" ,
               "ICD10_metastatic_cancer_diagnosis_code","ICD10_age_10_to_19","ICD10_CT_neighbor","ICD10_male_1",
               "ICD10_combination8","ICD10_limited_english" ,"ICD10_age_30s" ,"ICD10_age_10_to_19_3" ,"ICD10_veteran",
              "ICD10_rent_burden" ,"ICD10_age_40s" ,"ICD10_income_household_35_to_50_5" ,
               "ICD10_income_household_20_to_25_3" ,"ICD10_race_white" ,"ICD10_race_other" ",ICD10_disabled","ICD10_age_50s" ,
               "ICD10_education_graduate_3" ,"ICD10_poverty" ,"ICD10_Left" ,"ICD10_combination4" ,
               "ICD10_education_less_highschool" ,"ICD10_housing_units" ,"ICD10_race_pacific" ,
               "ICD10_education_highschool" ,"ICD10_income_individual_median","ICD10_income_household_50_to_75" ,
               "ICD10_education_stem_degree" ,"ICD10_divorced","ICD10_AR_neighbor" ,"ICD10_labor_force_participation_4" ,
               "ICD10_breast_cancer_diagnosis_desc" ,"ICD10_income_household_75_to_100_5" ,"ICD10_health_uninsured" ,
                "ICD10_farmer" ,"ICD10_female_1","ICD10_patient_age_Division",
               "ICD10_patient_age_income_household_six_figure_4" ,
               "ICD10_patient_age_age_30s_3" ,"ICD10_patient_age_NV_neighbor","ICD10_patient_age_health_uninsured" , 
               "ICD10_patient_age_payer_type" ,"ICD10_combination1_payer_type" ,"ICD10_male_patient_UT_neighbor",
               "ICD10_Left_combination4" ,"ICD10_breast_cancer_diagnosis_desc_income_household_25_to_35_4" ,
               "ICD10_patient_age_patient_race" ,
               "ICD10_metastatic_cancer_diagnosis_code_Division" ,
               "ICD10_patient_age_widowed_4" ]

rename = {new_columns[i]:(i+1) for i in range( len(new_columns))}
In [ ]:
train_copy = drop_column(train_copy,'new_feature52')
test_copy = drop_column(test_copy,'new_feature52')
In [ ]:
train_copy['new_feature53'] = train_copy['ICD10'].astype(str)+"_"+train_copy['patient_age'].astype(str)+"_"+train_copy['health_uninsured'].astype(str)
test_copy['new_feature53'] = test_copy['ICD10'].astype(str)+"_"+test_copy['patient_age'].astype(str)+"_"+test_copy['health_uninsured'].astype(str)
In [ ]:
train_copy = drop_column(train_copy,'new_feature53')
test_copy = drop_column(test_copy,'new_feature53')
In [ ]:
train_copy['new_feature54'] = train_copy['ICD10'].astype(str)+"_"+train_copy['combination1'].astype(str)+"_"+train_copy['payer_type'].astype(str)
test_copy['new_feature54'] = test_copy['ICD10'].astype(str)+"_"+test_copy['combination1'].astype(str)+"_"+test_copy['payer_type'].astype(str)
In [ ]:
train_copy['new_feature55'] = train_copy['ICD10'].astype(str)+"_"+train_copy['male_patient'].astype(str)+"_"+train_copy['UT_neighbor'].astype(str)
test_copy['new_feature55'] = test_copy['ICD10'].astype(str)+"_"+test_copy['male_patient'].astype(str)+"_"+test_copy['UT_neighbor'].astype(str)
In [ ]:
train_copy = drop_column(train_copy,'new_feature55')
test_copy = drop_column(test_copy,'new_feature55')
In [ ]:
train_copy['new_feature56'] = train_copy['ICD10'].astype(str)+"_"+train_copy['Left'].astype(str)+"_"+train_copy['combination4'].astype(str)
test_copy['new_feature56'] = test_copy['ICD10'].astype(str)+"_"+test_copy['Left'].astype(str)+"_"+test_copy['combination4'].astype(str)
In [ ]:
train_copy = drop_column(train_copy,'new_feature56')
test_copy = drop_column(test_copy,'new_feature56')
In [ ]:
train_copy['new_feature57'] = train_copy['ICD10'].astype(str)+"_"+train_copy['breast_cancer_diagnosis_desc'].astype(str)+"_"+train_copy['income_household_25_to_35_4'].astype(str)
test_copy['new_feature57'] = test_copy['ICD10'].astype(str)+"_"+test_copy['breast_cancer_diagnosis_desc'].astype(str)+"_"+test_copy['income_household_25_to_35_4'].astype(str)
In [ ]:
train_copy = drop_column(train_copy,'new_feature57')
test_copy = drop_column(test_copy,'new_feature57')
In [ ]:
train_copy['new_feature58'] = train_copy['ICD10'].astype(str)+"_"+train_copy['patient_age'].astype(str)+"_"+train_copy['patient_race'].astype(str)
test_copy['new_feature58'] = test_copy['ICD10'].astype(str)+"_"+test_copy['patient_age'].astype(str)+"_"+test_copy['patient_race'].astype(str)
In [ ]:
train_copy = drop_column(train_copy,'new_feature58')
test_copy = drop_column(test_copy,'new_feature58')
In [ ]:
train_copy['new_feature59'] = train_copy['ICD10'].astype(str)+"_"+train_copy['metastatic_cancer_diagnosis_code'].astype(str)+"_"+train_copy['Division'].astype(str)
test_copy['new_feature59'] = test_copy['ICD10'].astype(str)+"_"+test_copy['metastatic_cancer_diagnosis_code'].astype(str)+"_"+test_copy['Division'].astype(str)
In [ ]:
train_copy = drop_column(train_copy,'new_feature59')
test_copy = drop_column(test_copy,'new_feature59')
In [ ]:
train_copy['new_feature60'] = train_copy['ICD10'].astype(str)+"_"+train_copy['patient_age'].astype(str)+"_"+train_copy['widowed_4'].astype(str)
test_copy['new_feature60'] = test_copy['ICD10'].astype(str)+"_"+test_copy['patient_age'].astype(str)+"_"+test_copy['widowed_4'].astype(str)
In [ ]:
analysis = pd.read_csv('finaly.csv')
In [ ]:
analysis
In [ ]:
features_to_add = analysis[analysis["Mutual Information"]>0.1].Feature.unique()
In [ ]:
features_to_add
In [ ]:
train_copy.columns
In [ ]:
dropped
In [ ]:
here2
In [ ]:
from tqdm import tqdm

max_score = 0.8094293011407189
dropped = []
selected_features = list(set(test_copy.columns)-{"patient_zip3","breast_cancer_diagnosis_desc"})

for col in tqdm(selected_features, desc="Adding Features Progress") : 
    train_copy2 = train_copy.copy(deep =True)
    test_copy2 = test_copy.copy(deep =True)
    train_copy2 = drop_column(train_copy2, col)
    test_copy2 = drop_column(test_copy2, col)
    score1 = score(train_copy2, test_copy2)
    if score1>max_score : 
        dropped.append(col)
        max_score = score1
        print(f"imporved score to {max_score}")
        train_copy = train_copy2.copy(deep = True)
        test_copy = test_copy2.copy(deep = True)
        
    else : 
        continue
In [ ]:
dropped
In [ ]:
0.8091516782770249     | 19/212 [56:53<9:35:35, 178.94s/it]
In [ ]:
Adding Features Progress:  45%|██████████████████████▍                           | 95/212 [4:55:28<5:48:16, 178.60s/it]
In [ ]:
 
In [ ]:
train_copy2.patient_zip3
In [ ]:
train_copy.head()
In [ ]:
from tqdm import tqdm

max_score = 0.8094293011407189

for col in tqdm(features_to_add[140:], desc="Adding Features Progress"):
    
    a = ""
    b = ""
    c = ""
    counter = 0

    for j in train_copy.columns:
        if j in col and counter == 0:
            a = j
            counter += 1
        elif j in col and counter == 1:
            b = j
            counter += 1
        elif j in col and counter == 2:
            c = j
            counter += 1

        if counter == 3:
            break

    train_copy[col] = train_copy[a].astype(str) + "_" + train_copy[b].astype(str) + "_" + train_copy[c].astype(str)
    test_copy[col] = test_copy[a].astype(str) + "_" + test_copy[b].astype(str) + "_" + test_copy[c].astype(str)
    
    score1 = score(train_copy, test_copy)

    if score1 > max_score:
        print(f'Hey Aymen, we improved to {score1}')
        max_score = score1
    else:
        train_copy = drop_column(train_copy, col)
        test_copy = drop_column(test_copy, col)
In [ ]:
check_nan(test_copy)
In [ ]:
score(train_copy2 , test_copy2)
In [ ]:
train_copy.head()
In [ ]:
139/6561
In [ ]:
max_score
In [ ]:
test_copy.drop(["ICD10_patient_age_payer_type","ICD10_combination6_OR_neighbor","ICD10_breast_cancer_diagnosis_desc_income_household_25_to_35_4"] ,axis=1 , inplace =True)
train_copy.drop(["ICD10_patient_age_payer_type","ICD10_combination6_OR_neighbor","ICD10_breast_cancer_diagnosis_desc_income_household_25_to_35_4"] ,axis=1 , inplace =True)
In [ ]:
dropped
In [ ]:
class Stock : 
    n,_ = train.shape
    y = train.DiagPeriodL90D
    n_splits =5
    folds = StratifiedKFold(n_splits = n_splits )
In [ ]:
for i in range(20 ,49 ) : 
    train_copy.drop(f'new_feature{i}' , axis=1 , inplace =True) 
    test_copy.drop(f'new_feature{i}' , axis=1 , inplace =True) 
In [ ]:
import shap
In [ ]:
train_copy.drop('income_qcut' ,axis=1 , inplace =True)
In [ ]:
train_copy.head()
In [ ]:
def score(train_copy , test_copy):
    oof = train_copy[['DiagPeriodL90D']]
    folds = Stock.folds
    preds1=[]
    log = []
    X= train_copy.drop('DiagPeriodL90D' , axis=1)
    TEST= test_copy


    misclassified_indices_per_fold = []

    y = train_copy.DiagPeriodL90D

    for j,targ in enumerate(['DiagPeriodL90D']) : 
    #     y = train[targ]
        print(50*'--')
        print(f'Training k-Fold Model for Target {targ}')
        print(50*'--')
        for i,( train_index, test_index) in enumerate(folds.split(X, y)):

            print(50*'--')
            print(f'Fold {i+1}/{5}')
            print(50*'--')

            X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]
    #   class_weights = {0: 0.7 , 1 : 0.3} ,          
          # Train model
    #         stock_index.append(X_test.index)
            cat = CatBoostClassifier(random_seed=42 ,early_stopping_rounds=200, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3"], 
                                     loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                    text_features = ['breast_cancer_diagnosis_desc'] ,  

                                     logging_level='Silent') 


            cat.fit(X_train,y_train,eval_set=[(X_train,y_train),(X_test, y_test)])





    #         # Create a SHAP explainer object
    #         explainer = shap.TreeExplainer(cat)
    #         # Calculate SHAP values for the test set
    #         shap_values = explainer.shap_values(X_test )

    #         # Summary Plot to visualize feature importance
    #         shap.summary_plot(shap_values, X_test, feature_names=X.columns, plot_type='bar',max_display=len(X.columns))

            # Alternatively, you can plot a summary plot for a specific instance
            # For example, for the first instance in the test set



            calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
            calibrated_classifier.fit(X_train,y_train)

    #         calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
            # Fold Evaluation

    #         calibrated_classifier.fit(X_train, y_train)
    #         fold_pred   = model.predict_proba(X_test)
#             print(50*'**')
            y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
            y_pred = calibrated_classifier.predict(X_test )
    #         y_pred = [1 if i >0.78 else 0 for i in y_pred_prob ]
#             print(y_pred_prob , calibrated_classifier.predict_proba(X_test)[:, 1])
            accuracy = accuracy_score(y_test, y_pred)

    #         y_pred = [1 if i >0.55 else 0 for i in y_pred_prob ]
            roc_auc = roc_auc_score(y_test, y_pred_prob)
            conf_matrix = confusion_matrix(y_test, y_pred)
            loss = roc_auc

#             print(f'Accuracy: {accuracy:.4f}')
#             print(f'ROC AUC: {roc_auc:.4f}')

#             print('\nClassification Report:')
#             print(classification_report(y_test, y_pred))
#             print(f"log_loss validation Fold {i+1}/{5} is   : {loss}" )
            log.append(loss)    
#             print(50*'**')
#             #update oof


#             # Test Evaluation

#             test_proba = calibrated_classifier.predict_proba(TEST)

#             preds1.append(test_proba)








#             conf_mat  = confusion_matrix(y_test, y_pred) 
#             plt.figure(figsize=(8, 6))
#             sns.set(font_scale=1.2)
#             sns.set_style("whitegrid", {"axes.edgecolor": ".6", "grid.color": ".6"})

#             cmap = sns.color_palette("viridis", as_cmap=True)
#             heatmap = sns.heatmap(conf_matrix, annot=True, fmt='d', cmap=cmap, annot_kws={'size': 14}, cbar=False)

#             heatmap.set_title('Confusion Matrix', fontdict={'fontsize': 16})
#             heatmap.set_xlabel('Predicted', fontdict={'fontsize': 14})
#             heatmap.set_ylabel('True', fontdict={'fontsize': 14})



#             fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
#             roc_auc = auc(fpr, tpr)

#             fig = go.Figure()
#             fig.add_trace(go.Scatter(x=fpr, y=tpr, mode='lines', 
#                                      line=dict(color='#FF4505', width=5),
#                                      name=f'AUC = {roc_auc:.2f}'))

#             fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', 
#                                      line=dict(color='navy', width=2, dash='dash'),
#                                      name='Random'))

#             fig.update_layout(
#                 title='ROC Curve',
#                 xaxis=dict(title='False Positive Rate'),
#                 yaxis=dict(title='True Positive Rate'),
#                 legend=dict(x=0.02, y=0.98),
#                 width=800, height=800
#             )

#             fig.show()

#             threshold = 0.5
#             y_pred_binary = (y_pred_prob > threshold).astype(int)
#             misclassified_indices = np.where(y_pred_binary != y_test)[0]
#             misclassified_indices_per_fold.append(misclassified_indices)


#     plt.show()
#     print(50*'##')
    print(f"The overall loss is {np.array(log).mean()}")



#     all_misclassified_indices = np.concatenate(misclassified_indices_per_fold)

#     print("Indices of misclassified instances:")
#     print(all_misclassified_indices) 
    return np.array(log).mean()
In [ ]:
score(train_copy , test_copy)
In [ ]:
# train_copy.to_csv('best_train.csv' , index = False)
# test_copy.to_csv('best_test.csv' , index = False)
In [ ]:
# model_path = 'cat_model.cbm'
# cat.save_model(model_path)
In [ ]:
# train_copy.to_csv('last_train.csv' , index = False)
# test_copy.to_csv('last_test.csv' , index = False)
In [ ]:
# model_path = 'best_cat.cbm'
# cat.save_model(model_path) #0.8099
In [ ]:
 
In [ ]:
 
In [ ]:
train_copy.head()
In [ ]:
train_copy.shape
In [ ]:
# neighbors_dict = {
#     'CA': ['OR', 'NV', 'AZ'],
#     'TX': ['NM', 'OK', 'LA', 'AR'],
#     'ID': ['WA', 'OR', 'MT', 'WY', 'UT', 'NV'],
#     'NY': ['VT', 'MA', 'CT', 'NJ', 'PA'],
#     'IL': ['WI', 'IA', 'MO', 'KY', 'IN'],
#     'OR': ['WA', 'ID', 'CA', 'NV'],
#     'MI': ['WI', 'IN', 'OH'],
#     'MT': ['ID', 'WY', 'SD', 'ND'],
#     'KY': ['IN', 'OH', 'WV', 'VA', 'TN', 'MO', 'IL'],
#     'OH': ['MI', 'IN', 'KY', 'WV', 'PA'],
#     'IN': ['MI', 'OH', 'KY', 'IL'],
#     'FL': ['GA', 'AL'],
#     'CO': ['WY', 'NE', 'KS', 'OK', 'NM', 'UT'],
#     'VA': ['MD', 'DC', 'WV', 'KY', 'TN', 'NC'],
#     'GA': ['FL', 'AL', 'TN', 'NC', 'SC'],
#     'KS': ['NE', 'MO', 'OK', 'CO'],
#     'WI': ['MI', 'IL', 'IA', 'MN'],
#     'PA': ['NY', 'NJ', 'DE', 'MD', 'WV', 'OH'],
#     'NM': ['CO', 'OK', 'TX', 'AZ', 'UT'],
#     'WA': ['ID', 'OR'],
#     'MN': ['WI', 'IA', 'SD', 'ND'],
#     'NC': ['VA', 'TN', 'GA', 'SC'],
#     'AL': ['FL', 'GA', 'TN', 'MS'],
#     'SC': ['NC', 'GA'],
#     'LA': ['TX', 'AR', 'MS'],
#     'IA': ['MN', 'WI', 'IL', 'MO', 'NE', 'SD'],
#     'TN': ['KY', 'VA', 'NC', 'GA', 'AL', 'MS', 'AR', 'MO'],
#     'MD': ['PA', 'WV', 'VA', 'DE'],
#     'HI': ['island'],
#     'NE': ['SD', 'WY', 'CO', 'KS', 'IA', 'MO'],
#     'AZ': ['CA', 'NV', 'UT', 'CO', 'NM'],
#     'MO': ['IA', 'IL', 'KY', 'TN', 'AR', 'OK', 'KS', 'NE'],
#     'NV': ['CA', 'OR', 'ID', 'UT', 'AZ'],
#     'SD': ['ND', 'MN', 'IA', 'NE', 'WY', 'MT'],
#     'DC': ['MD', 'VA'],
#     'AR': ['MO', 'TN', 'MS', 'LA', 'TX', 'OK'],
#     'UT': ['ID', 'WY', 'CO', 'NM', 'AZ', 'NV'],
#     'WV': ['PA', 'OH', 'KY', 'VA', 'MD'],
#     'ND': ['MN', 'SD', 'MT'],
#     'OK': ['KS', 'MO', 'AR', 'TX', 'CO', 'NM'],
#     'WY': ['MT', 'SD', 'NE', 'CO', 'UT', 'ID'],
#     'DE': ['PA', 'MD', 'NJ'],
#     'MS': ['TN', 'AL', 'LA', 'AR'],
#     'AK': ['island'],
# }

# # Create a new column 'neighbors' by mapping the values from the dictionary
# train_copy['neighbors'] = train_copy['patient_state'].map(neighbors_dict)
# test_copy['neighbors'] = test_copy['patient_state'].map(neighbors_dict)
In [ ]:
# train_copy['neighbors_str'] = train_copy['neighbors'].apply(lambda x: ','.join(map(str, x)) if isinstance(x, list) else str(x))
# test_copy['neighbors_str'] = test_copy['neighbors'].apply(lambda x: ','.join(map(str, x)) if isinstance(x, list) else str(x))
# train_copy.drop('neighbors' ,axis=1 , inplace = True)
# test_copy.drop('neighbors' ,axis=1 , inplace = True)
In [ ]:
# all_encode_train = pd.read_csv('train_all_enc.csv')
# all_encode_test = pd.read_csv('test_all_enc.csv')
In [ ]:
# all_encode_train = all_encode_train.drop(9336)
# all_encode_train = all_encode_train.drop(all_encode_train[all_encode_train['age_under_10'].isna()].index)
In [ ]:
# train_copy["disabled_ohe"] = all_encode_train["disabled_ohe"] 
# test_copy["disabled_ohe"] = all_encode_test["disabled_ohe"] 


# train_copy["education_graduate_ohe"] = all_encode_train["education_graduate_ohe"] 
# test_copy["education_graduate_ohe"] = all_encode_test["education_graduate_ohe"] 


train_copy["payer_type_2_he"] = all_encode_train["payer_type_2_he"] 
test_copy["payer_type_2_he"] = all_encode_test["payer_type_2_he"] 
In [ ]:
the best cat
In [ ]:
# kkkkk
In [ ]:
zip_file_path = "archive (7).zip"
with zipfile.ZipFile(zip_file_path , 'r') as zip_ref : 
    zip_ref.extractall()
In [ ]:
train2 = pd.read_csv('new_train (1).csv')
test2 = pd.read_csv('new_test (1).csv')
In [ ]:
train2 = train2.drop(train2[train2['age_under_10'].isna()].index)
train2 = train2.drop(9336)
In [ ]:
train_copy = pd.read_csv('last_train.csv')

test_copy = pd.read_csv('last_test.csv')
In [ ]:
to_pcs = [i for i in train_copy.iloc[:, :82].columns if train_copy[i].dtype == float]
In [ ]:
X_pcs_train = train_copy[to_pcs]
X_pcs_test = test_copy[to_pcs]
In [ ]:
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA


scaler = StandardScaler()
X_pcs_train_scaled = scaler.fit_transform(X_pcs_train)
X_pcs_test_scaled = scaler.transform(X_pcs_test)


pca = PCA().fit(X_pcs_train_scaled)
explained_variance_ratio = pca.explained_variance_ratio_

plt.plot(explained_variance_ratio.cumsum())
plt.xlabel('Number of Components')
plt.ylabel('Cumulative Explained Variance')
plt.show()

n_components = 50 
pca = PCA(n_components=n_components)
X_pcs_train_reduced = pca.fit_transform(X_pcs_train_scaled)
X_pcs_test_reduced = pca.transform(X_pcs_test_scaled)
In [ ]:
columns = [f'PC{i+1}' for i in range(X_pcs_train_reduced.shape[1])]
X_pcs_train_df = pd.DataFrame(X_pcs_train_reduced, columns=columns)
X_pcs_test_df = pd.DataFrame(X_pcs_test_reduced, columns=columns)
In [ ]:
 
In [ ]:
# train_copy[["underweight","obese","young_ind","desolated","home_wealth","air_quality","wealth_index","education_ratio","hh_income_ratio","age_ratio","race_ration"]] = train2[["underweight","obese","young_ind","desolated","home_wealth","air_quality","wealth_index","education_ratio","hh_income_ratio","age_ratio","race_ration"]]
# test_copy[["underweight","obese","young_ind","desolated","home_wealth","air_quality","wealth_index","education_ratio","hh_income_ratio","age_ratio","race_ration"]] = test2[["underweight","obese","young_ind","desolated","home_wealth","air_quality","wealth_index","education_ratio","hh_income_ratio","age_ratio","race_ration"]]
In [ ]:
class Stock : 
    n,_ = train_copy.shape
    y = train_copy.DiagPeriodL90D
    n_splits =5
    folds = StratifiedKFold(n_splits = n_splits )
In [ ]:
# for column in train_copy.columns:
#     if train_copy[column].dtype == 'float64':  # Check if the column is of float type
#         train_copy[column] = train_copy[column].round()

# # Alternatively, you can use the apply function to round all float columns
# train_copy = train_copy.apply(lambda x: x.round() if x.dtype == 'float64' else x)
# test_copy = test_copy.apply(lambda x: x.round() if x.dtype == 'float64' else x)
In [ ]:
# train_copy.drop(['education_graduate','education_stem_degree','self_employed',
#                                           'health_uninsured','age_40s','race_white','race_native',
#                                           'age_50s','patient_zip3','family_size','farmer','race_pacific','divorced'] ,axis=1 , inplace =True) 


# test_copy.drop(['education_graduate','education_stem_degree','self_employed',
#                                           'health_uninsured','age_40s','race_white','race_native',
#                                           'age_50s','patient_zip3','family_size','farmer','race_pacific','divorced'] ,axis=1 , inplace =True) 
In [ ]:
# train_copy['best_4_conbin'] = train_copy['payer_type'].astype(str)+train_copy['patient_age'].astype(str)+train_copy['new_feature17'].astype(str)
# test_copy['best_4_conbin'] = test_copy['payer_type'].astype(str)+test_copy['patient_age'].astype(str)+test_copy['new_feature17'].astype(str)
In [ ]:
# ratio_negative_to_positive = (y.value_counts()[0] / y.value_counts()[1])
# class Stock : 
#     n,_ = train_copy.shape
#     y = train_copy.DiagPeriodL90D
#     n_splits =5
#     folds = StratifiedKFold(n_splits = n_splits )
In [ ]:
# num_to_cat = [i for i in test_copy.columns if test_copy[i].dtype == float]
In [ ]:
# y = train_copy.DiagPeriodL90D
# # train_copy = train_copy[['breast_cancer_diagnosis_code','metastatic_cancer_diagnosis_code','patient_zip3','patient_age','payer_type',
# #         'patient_state','breast_cancer_diagnosis_desc']]
# # test_copy = test_copy[['breast_cancer_diagnosis_code','metastatic_cancer_diagnosis_code','patient_zip3','patient_age','payer_type',
# #         'patient_state','breast_cancer_diagnosis_desc']]

# # train_copy['DiagPeriodL90D'] = y 

# X = train_copy.drop('DiagPeriodL90D' , axis=1 )
# from imblearn.under_sampling import TomekLinks
# from sklearn.model_selection import train_test_split
# import pandas as pd



# # Create an instance of TomekLinks
# tomek_links = TomekLinks(sampling_strategy='auto',)

# # Fit and transform the training data
# X, y = tomek_links.fit_resample(X, y)

# train_copy = X
# train_copy['DiagPeriodL90D'] = y 
In [ ]:
# train1 = train_copy[train_copy['ICD10']==1]
# train2 = train_copy[train_copy['ICD10']==0]
In [ ]:
# train1.drop('ICD10' , axis=1 , inplace =True)
# train2.drop('ICD10' , axis=1 , inplace =True)
In [ ]:
# a = train_copy.breast_cancer_diagnosis_desc
# b= test_copy.breast_cancer_diagnosis_desc
train_copy = train_copy.iloc[:,-129:]
test_copy = test_copy.iloc[:,-128:]
# train_copy['breast_cancer_diagnosis_desc'] = a
# test_copy['breast_cancer_diagnosis_desc'] = b
In [ ]:
train_copy = pd.concat([X_pcs_train_df,train_copy ] , axis=1 ) 
test_copy = pd.concat([X_pcs_test_df,test_copy ] , axis=1 ) 
In [ ]:
TO_drop = ["CA_neighbor","TX_neighbor","ID_neighbor","NY_neighbor","IL_neighbor","MI_neighbor","OR_neighbor","MT_neighbor","KY_neighbor","OH_neighbor","IN_neighbor","FL_neighbor","CO_neighbor","GA_neighbor","VA_neighbor","MD_neighbor","KS_neighbor","WI_neighbor","PA_neighbor","NM_neighbor","WA_neighbor","MN_neighbor","NC_neighbor","AL_neighbor","SC_neighbor","LA_neighbor","IA_neighbor","TN_neighbor","NE_neighbor","AZ_neighbor","MO_neighbor","NV_neighbor","SD_neighbor","DC_neighbor","AR_neighbor","UT_neighbor","WV_neighbor","ND_neighbor","OK_neighbor","WY_neighbor","DE_neighbor","NJ_neighbor","MS_neighbor","CT_neighbor","MA_neighbor"]
train_copy.drop(TO_drop ,axis=1 , inplace =True)
test_copy.drop(TO_drop ,axis=1 , inplace =True)
In [ ]:
oof = train_copy[['DiagPeriodL90D']]
folds = Stock.folds
preds1=[]
log = []
X= train_copy.drop('DiagPeriodL90D' , axis=1)
TEST= test_copy
oof_predictions_catboost = np.zeros(len(X))


misclassified_indices_per_fold = []

y = train_copy.DiagPeriodL90D

for j,targ in enumerate(['DiagPeriodL90D']) : 
#     y = train[targ]
    print(50*'--')
    print(f'Training k-Fold Model for Target {targ}')
    print(50*'--')
    for i,( train_index, test_index) in enumerate(folds.split(X, y)):

        print(50*'--')
        print(f'Fold {i+1}/{5}')
        print(50*'--')
        
        X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]
#   class_weights = {0: 0.7 , 1 : 0.3} ,          
      # Train model
#         stock_index.append(X_test.index)
        cat = CatBoostClassifier(random_seed=42 ,early_stopping_rounds=200, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3" ], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,  
                         
                                 logging_level='Silent', 
                                 
#                                  **{'iterations': 761,
#  'learning_rate': 0.06633394185843565,
#  'depth': 7,
#  'l2_leaf_reg': 4.513845288655649}
#                                  **{'iterations': 838,
#  'learning_rate': 0.0206258759084974,
#  'depth': 7,
#  'l2_leaf_reg': 8.763527862659274}
                                 
                                 
                            
) 
    
    
        cat.fit(X_train,y_train,eval_set=[(X_train,y_train),(X_test, y_test)], plot= True)
        
        plot_features = pd.DataFrame()
        plot_features['features'] = cat.feature_names_
        plot_features['features_importance'] = cat.feature_importances_
        n_top_feats = 60
        plt.figure(figsize=(16, 16))
        sns.barplot(data=plot_features.sort_values(by='features_importance', ascending=False).head(n_top_feats), x='features_importance', y='features');
        plt.title(f'{n_top_feats} TOP feature importance');
        plt.plot()
       


#         # Create a SHAP explainer object
#         explainer = shap.TreeExplainer(cat)
#         # Calculate SHAP values for the test set
#         shap_values = explainer.shap_values(X_test )

#         # Summary Plot to visualize feature importance
#         shap.summary_plot(shap_values, X_test, feature_names=X.columns, plot_type='bar',max_display=len(X.columns))

        # Alternatively, you can plot a summary plot for a specific instance
        # For example, for the first instance in the test set
        
        
        
        calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        calibrated_classifier.fit(X_train,y_train)
        
#         calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        # Fold Evaluation
        
#         calibrated_classifier.fit(X_train, y_train)
#         fold_pred   = model.predict_proba(X_test)
        print(50*'**')
        y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
        y_pred = calibrated_classifier.predict(X_test )
#         y_pred = [1 if i >0.78 else 0 for i in y_pred_prob ]
        print(y_pred_prob , calibrated_classifier.predict_proba(X_test)[:, 1])
        accuracy = accuracy_score(y_test, y_pred)
        
#         y_pred = [1 if i >0.55 else 0 for i in y_pred_prob ]
        roc_auc = roc_auc_score(y_test, y_pred_prob)
        conf_matrix = confusion_matrix(y_test, y_pred)
        loss = roc_auc

        print(f'Accuracy: {accuracy:.4f}')
        print(f'ROC AUC: {roc_auc:.4f}')

        print('\nClassification Report:')
        print(classification_report(y_test, y_pred))
        print(f"log_loss validation Fold {i+1}/{5} is   : {loss}" )
        log.append(loss)    
        print(50*'**')
        #update oof
        

        # Test Evaluation
        
        test_proba = calibrated_classifier.predict_proba(TEST)

        preds1.append(test_proba)
        
        
        



            
            
        conf_mat  = confusion_matrix(y_test, y_pred) 
        plt.figure(figsize=(8, 6))
        sns.set(font_scale=1.2)
        sns.set_style("whitegrid", {"axes.edgecolor": ".6", "grid.color": ".6"})

        cmap = sns.color_palette("viridis", as_cmap=True)
        heatmap = sns.heatmap(conf_matrix, annot=True, fmt='d', cmap=cmap, annot_kws={'size': 14}, cbar=False)

        heatmap.set_title('Confusion Matrix', fontdict={'fontsize': 16})
        heatmap.set_xlabel('Predicted', fontdict={'fontsize': 14})
        heatmap.set_ylabel('True', fontdict={'fontsize': 14})
        
        
        
        fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
        roc_auc = auc(fpr, tpr)

        fig = go.Figure()
        fig.add_trace(go.Scatter(x=fpr, y=tpr, mode='lines', 
                                 line=dict(color='#FF4505', width=5),
                                 name=f'AUC = {roc_auc:.2f}'))

        fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', 
                                 line=dict(color='navy', width=2, dash='dash'),
                                 name='Random'))

        fig.update_layout(
            title='ROC Curve',
            xaxis=dict(title='False Positive Rate'),
            yaxis=dict(title='True Positive Rate'),
            legend=dict(x=0.02, y=0.98),
            width=800, height=800
        )

        fig.show()
        
        threshold = 0.5
        y_pred_binary = (y_pred_prob > threshold).astype(int)
        misclassified_indices = np.where(y_pred_binary != y_test)[0]
        misclassified_indices_per_fold.append(misclassified_indices)
        
        
        fold_predictions_catboost = calibrated_classifier.predict_proba(X_test)[:, 1]

        # Store the predictions for this fold in the oof_predictions array
        oof_predictions_catboost[test_index] = fold_predictions_catboost

        all_features = X.columns.tolist()

        # Obtenez les noms des fonctionnalités avec une importance nulle dans le modèle CatBoost
        zero_importance_features = [feature for feature, importance in zip(all_features, cat.feature_importances_) if importance == 0]

        # Affichez les fonctionnalités avec une importance nulle
        print("0 importance features :")
        print(zero_importance_features)
        
plt.show()
print(50*'##')

print(f"The overall loss is {np.array(log).mean()}")



all_misclassified_indices = np.concatenate(misclassified_indices_per_fold)

print("Indices of misclassified instances:")
print(all_misclassified_indices) 
In [ ]:
np.absolute(train_copy.corr()['bmi']).sort_values(ascending=False).shape
In [ ]:
 
In [ ]:
odd = ["patient_state","patient_zip3","Region","Division"]
In [ ]:
for feat in odd : 
    print(train_copy[feat].nunique())
In [ ]:
age_median age_under_10 age_10_to_19
In [ ]:
group_by_cols = list()

for col in test_copy.columns :
    if test_copy[col].dtype == float : 
        group_by_cols.append(col)
In [ ]:
group_by_cols = group_by_cols +["patient_age"]
In [ ]:
aggregation_strategies = ['mean', 'max', 'min', 'std', 'median', 'sum', 'count', 'var', 'quantile', 'skew']

cols_to_agg = ["patient_state","payer_type","Region","Division"]
In [ ]:
y = train_copy.DiagPeriodL90D
n = train_copy.shape[0]
train_copy.drop('DiagPeriodL90D' ,axis=1 , inplace  = True)
In [ ]:
AllData = pd.concat([train_copy,test_copy],axis=0)
In [ ]:
col_to_agg
In [ ]:
for col_to_agg in cols_to_agg:
    for col in group_by_cols:
        for strategy in aggregation_strategies:
            AllData[f'{col_to_agg} {strategy} by {col}'] = AllData.groupby(col_to_agg)[col].transform(strategy)

# AllData.drop(group_by_cols,axis=1,inplace=True)
# AllData.drop(group_by_cols,axis=1,inplace=True)
In [ ]:
train_copy = AllData.iloc[:n]
test_copy = AllData.iloc[n:]
train_copy["DiagPeriodL90D"] = y 
In [ ]:
 
In [ ]:
f = train_copy[['misclassified']]
folds = Stock.folds
preds1=[]
log = []
X= train_copy.drop('misclassified' , axis=1)
TEST= test_copy
oof_predictions_catboost = np.zeros(len(X))


misclassified_indices_per_fold = []

y = train_copy.misclassified

for j,targ in enumerate(['misclassified']) : 
#     y = train[targ]
    print(50*'--')
    print(f'Training k-Fold Model for Target {targ}')
    print(50*'--')
    for i,( train_index, test_index) in enumerate(folds.split(X, y)):

        print(50*'--')
        print(f'Fold {i+1}/{5}')
        print(50*'--')
        
        X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]
#   class_weights = {0: 0.7 , 1 : 0.3} ,          
      # Train model
#         stock_index.append(X_test.index)
        cat = CatBoostClassifier(random_seed=42 ,early_stopping_rounds=200, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3" ], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,  
                         
                                 logging_level='Silent', class_weights={0 : 0.99999 , 1 : 0.0001}
                                 
#                                  **{'iterations': 761,
#  'learning_rate': 0.06633394185843565,
#  'depth': 7,
#  'l2_leaf_reg': 4.513845288655649}
#                                  **{'iterations': 838,
#  'learning_rate': 0.0206258759084974,
#  'depth': 7,
#  'l2_leaf_reg': 8.763527862659274}
                                 
                                 
                            
) 
    
    
        cat.fit(X_train,y_train,eval_set=[(X_train,y_train),(X_test, y_test)], plot= True)
        
        plot_features = pd.DataFrame()
        plot_features['features'] = cat.feature_names_
        plot_features['features_importance'] = cat.feature_importances_
        n_top_feats = 60
        plt.figure(figsize=(16, 16))
        sns.barplot(data=plot_features.sort_values(by='features_importance', ascending=False).head(n_top_feats), x='features_importance', y='features');
        plt.title(f'{n_top_feats} TOP feature importance');
        plt.plot()
       


#         # Create a SHAP explainer object
#         explainer = shap.TreeExplainer(cat)
#         # Calculate SHAP values for the test set
#         shap_values = explainer.shap_values(X_test )

#         # Summary Plot to visualize feature importance
#         shap.summary_plot(shap_values, X_test, feature_names=X.columns, plot_type='bar',max_display=len(X.columns))

        # Alternatively, you can plot a summary plot for a specific instance
        # For example, for the first instance in the test set
        
        
        
        calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        calibrated_classifier.fit(X_train,y_train)
        
#         calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        # Fold Evaluation
        
#         calibrated_classifier.fit(X_train, y_train)
#         fold_pred   = model.predict_proba(X_test)
        print(50*'**')
        y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
        y_pred = calibrated_classifier.predict(X_test )
#         y_pred = [1 if i >0.78 else 0 for i in y_pred_prob ]
        print(y_pred_prob , calibrated_classifier.predict_proba(X_test)[:, 1])
        accuracy = accuracy_score(y_test, y_pred)
        
#         y_pred = [1 if i >0.55 else 0 for i in y_pred_prob ]
        roc_auc = roc_auc_score(y_test, y_pred_prob)
        conf_matrix = confusion_matrix(y_test, y_pred)
        loss = roc_auc

        print(f'Accuracy: {accuracy:.4f}')
        print(f'ROC AUC: {roc_auc:.4f}')

        print('\nClassification Report:')
        print(classification_report(y_test, y_pred))
        print(f"log_loss validation Fold {i+1}/{5} is   : {loss}" )
        log.append(loss)    
        print(50*'**')
        #update oof
        

        # Test Evaluation
        
        test_proba = calibrated_classifier.predict_proba(TEST)

        preds1.append(test_proba)
        
        
        



            
            
        conf_mat  = confusion_matrix(y_test, y_pred) 
        plt.figure(figsize=(8, 6))
        sns.set(font_scale=1.2)
        sns.set_style("whitegrid", {"axes.edgecolor": ".6", "grid.color": ".6"})

        cmap = sns.color_palette("viridis", as_cmap=True)
        heatmap = sns.heatmap(conf_matrix, annot=True, fmt='d', cmap=cmap, annot_kws={'size': 14}, cbar=False)

        heatmap.set_title('Confusion Matrix', fontdict={'fontsize': 16})
        heatmap.set_xlabel('Predicted', fontdict={'fontsize': 14})
        heatmap.set_ylabel('True', fontdict={'fontsize': 14})
        
        
        
        fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
        roc_auc = auc(fpr, tpr)

        fig = go.Figure()
        fig.add_trace(go.Scatter(x=fpr, y=tpr, mode='lines', 
                                 line=dict(color='#FF4505', width=5),
                                 name=f'AUC = {roc_auc:.2f}'))

        fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', 
                                 line=dict(color='navy', width=2, dash='dash'),
                                 name='Random'))

        fig.update_layout(
            title='ROC Curve',
            xaxis=dict(title='False Positive Rate'),
            yaxis=dict(title='True Positive Rate'),
            legend=dict(x=0.02, y=0.98),
            width=800, height=800
        )

        fig.show()
        
        threshold = 0.5
        y_pred_binary = (y_pred_prob > threshold).astype(int)
        misclassified_indices = np.where(y_pred_binary != y_test)[0]
        misclassified_indices_per_fold.append(misclassified_indices)
        
        
        fold_predictions_catboost = calibrated_classifier.predict_proba(X_test)[:, 1]

        # Store the predictions for this fold in the oof_predictions array
        oof_predictions_catboost[test_index] = fold_predictions_catboost

        all_features = X.columns.tolist()

        # Obtenez les noms des fonctionnalités avec une importance nulle dans le modèle CatBoost
        zero_importance_features = [feature for feature, importance in zip(all_features, cat.feature_importances_) if importance == 0]

        # Affichez les fonctionnalités avec une importance nulle
        print("0 importance features :")
        print(zero_importance_features)
        
plt.show()
print(50*'##')

print(f"The overall loss is {np.array(log).mean()}")



all_misclassified_indices = np.concatenate(misclassified_indices_per_fold)

print("Indices of misclassified instances:")
print(all_misclassified_indices) 
In [ ]:
train_copy['misclassified'] = ([1 if i>=0.5 else 0 for i in  oof_predictions_catboost ] == y).astype(int)
In [ ]:
train_copy.drop('DiagPeriodL90D' ,axis=1 , inplace =True)
In [ ]:
train_copy['misclassified'] = ([1 if i>=0.5 else 0 for i in  oof_predictions_catboost ] == y).astype(int)
In [ ]:
to_drop = list()

corr_matrix = test_copy.corr()


# Iterating over rows starting from the second one, because position [0, 0] will be self-correlation which is 1
for i in range(1, len(corr_matrix)):
    # Iterating over columns of the row. Only going under the diagonal.
    for j in range(i):
        # See if the correlation between two features are more than a selected threshold
        if corr_matrix.iloc[i, j] >= 0.98:
            # Then keep the one from thos two which correlates with target better
            if abs(pd.concat([X[corr_matrix.index[i]], y], axis=1).corr().iloc[0][1]) > abs(pd.concat([X[corr_matrix.columns[j]], y], axis=1).corr().iloc[0][1]):
                to_drop.append(corr_matrix.columns[j])
            else:
                to_drop.append(corr_matrix.index[i])

to_drop = list(set(to_drop))
In [ ]:
to_drop
In [ ]:
a = train_copy.iloc[[   2,    4,    6,    7,    8,   10,   11,   12,   13,   16,   17,
          20,   21,   22,   24,   25,   30,   33,   37,   38,   39,   41,
          46,   50,   55,   59,   76,   79,   82,   83,   89,   90,   96,
          99,  109,  119,  126,  135,  137,  143,  149,  154,  158,  159,
         161,  164,  167,  181,  183,  191,  201,  226,  227,  229,  231,
         238,  240,  245,  249,  252,  256,  258,  262,  270,  281,  297,
         301,  317,  318,  320,  322,  326,  328,  331,  337,  339,  342,
         345,  348,  356,  358,  370,  379,  384,  387,  393,  398,  400,
         402,  415,  419,  426,  427,  428,  431,  433,  434,  438,  440,
         443,  444,  449,  451,  452,  454,  456,  458,  459,  463,  466,
         475,  488,  489,  495,  502,  504,  507,  509,  513,  517,  519,
         521,  523,  524,  530,  545,  548,  550,  551,  556,  560,  561,
         563,  564,  570,  578,  587,  596,  598,  606,  609,  618,  633,
         637,  649,  653,  656,  657,  659,  664,  665,  673,  684,  686,
         704,  708,  739,  740,  741,  742,  743,  746,  753,  767,  771,
         772,  775,  799,  805,  808,  818,  819,  820,  822,  824,  832,
         837,  844,  845,  854,  857,  862,  864,  865,  867,  869,  870,
         876,  887,  889,  892,  893,  911,  917,  928,  931,  935,  938,
         955,  958,  959,  973,  984,  991,  997, 1012, 1015, 1018, 1039,
        1043, 1046, 1056, 1058, 1063, 1064, 1070, 1076, 1084, 1088, 1092,
        1109, 1110, 1115, 1116, 1118, 1134, 1136, 1141, 1146, 1147, 1150,
        1151, 1158, 1160, 1164, 1184, 1199, 1203, 1204, 1207, 1208, 1218,
        1220, 1225, 1237, 1253, 1266, 1269, 1273, 1277, 1279, 1293, 1298,
        1302, 1308, 1309, 1310, 1311, 1313, 1330, 1332, 1333, 1335, 1344,
        1350, 1357, 1363, 1365, 1366, 1368, 1375, 1379, 1386, 1398, 1403,
        1406, 1410, 1413, 1414, 1416, 1419, 1442, 1449, 1454, 1455, 1457,
        1458, 1464, 1474, 1475, 1476, 1488, 1489, 1492, 1495, 1497, 1509,
        1514, 1519, 1531, 1535, 1552, 1555, 1556, 1558, 1562, 1564, 1566,
        1570, 1576, 1578, 1579, 1582, 1590, 1591, 1595, 1602, 1611, 1612,
        1614, 1630, 1641, 1644, 1647, 1648, 1650, 1653, 1654, 1661, 1673,
        1676, 1681, 1684, 1685, 1692, 1695, 1697, 1702, 1717, 1720, 1727,
        1729, 1730, 1737, 1738, 1739, 1740, 1744, 1753, 1754, 1755, 1765,
        1768, 1771, 1773, 1781, 1784, 1787, 1789, 1793, 1795, 1796, 1797,
        1805, 1808, 1809, 1816, 1832, 1843, 1844, 1846, 1851, 1856, 1860,
        1869, 1873, 1877, 1878, 1884, 1885, 1887, 1893, 1894, 1907, 1910,
        1918, 1922, 1929, 1930, 1934, 1936, 1938, 1944, 1945, 1952, 1954,
        1957, 1961, 1966, 1972, 1973, 1974, 1976, 1980, 1986, 1991, 1993,
        1995, 1996, 2000, 2026, 2034, 2038, 2040, 2043, 2062, 2063, 2068,
        2072, 2073, 2074, 2077, 2079, 2093, 2095, 2101, 2118, 2126, 2142,
        2150, 2151, 2152, 2164, 2166, 2171, 2175, 2188, 2191, 2195, 2199,
        2202, 2205, 2209, 2210, 2218, 2220, 2223, 2227, 2228, 2236, 2240,
        2245, 2249, 2251, 2262, 2268, 2276, 2288, 2295, 2303, 2309, 2311,
        2317, 2318, 2321, 2335, 2346, 2349, 2350, 2356, 2357, 2358, 2361,
        2365, 2374, 2375, 2387, 2399, 2401, 2424, 2427, 2429, 2437, 2439,
        2443, 2451, 2456, 2460, 2468, 2469, 2471, 2472, 2476, 2486, 2490,
        2492, 2496, 2498, 2504, 2505, 2507, 2508, 2509, 2512, 2515, 2516,
        2517, 2535, 2536, 2540, 2545, 2546, 2549, 2550, 2557, 2560, 2563,
        2574, 2576, 2580]]
In [ ]:
a
In [ ]:
train_copy[(train_copy["metastatic_cancer_diagnosis_code"] == "C77.3")&(train_copy["breast_cancer_diagnosis_code"] == "C50.112")&(train_copy["patient_state"] == "TX")]
In [ ]:
misclassified_indices_per_fold
In [ ]:
C50.112	
In [ ]:
train_copy[train_copy['breast_cancer_diagnosis_code'] =="C50.919"]
In [ ]:
 
In [ ]:
train_copy.head()
In [ ]:
cat_test_pred =pd.DataFrame()
cat_test_pred['perd'] = np.mean(preds1 , axis=0)[:,1]
cat_test_pred.to_csv('cat_test_predd.csv' , index =False)
In [ ]:
The overall loss is 0.8100205207295043
In [ ]:
def build_model(train_copy, target = 'DiagPeriodL90D') :
    
    y = train_copy[['DiagPeriodL90D']]
    folds = Stock.folds
    preds1=[]
    log = []
    X= train_copy.drop('DiagPeriodL90D' , axis=1)
    TEST= test_copy
    oof_predictions_catboost = np.zeros(len(X))


    misclassified_indices_per_fold = []

    y = train_copy.DiagPeriodL90D

    for j,targ in enumerate(['DiagPeriodL90D']) : 
    #     y = train[targ]
        print(50*'--')
        print(f'Training k-Fold Model for Target {targ}')
        print(50*'--')
        for i,( train_index, test_index) in enumerate(folds.split(X, y)):

            print(50*'--')
            print(f'Fold {i+1}/{5}')
            print(50*'--')

            X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]
    #   class_weights = {0: 0.7 , 1 : 0.3} ,          
          # Train model
    #         stock_index.append(X_test.index)
            cat = CatBoostClassifier(random_seed=42 ,early_stopping_rounds=200, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3" , "patient_age_5"], 
                                     loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                    text_features = ['breast_cancer_diagnosis_desc'] ,  

                                     logging_level='Silent', ) 

    #                                  **{'iterations': 761,
    #  'learning_rate': 0.06633394185843565,
    #  'depth': 7,
    #  'l2_leaf_reg': 4.513845288655649}
    #                                  **{'iterations': 838,
    #  'learning_rate': 0.0206258759084974,
    #  'depth': 7,
    #  'l2_leaf_reg': 8.763527862659274}



    # ) 


            cat.fit(X_train,y_train,eval_set=[(X_train,y_train),(X_test, y_test)])

#             plot_features = pd.DataFrame()
#             plot_features['features'] = cat.feature_names_
#             plot_features['features_importance'] = cat.feature_importances_
#             n_top_feats = 60
#             plt.figure(figsize=(16, 16))
#             sns.barplot(data=plot_features.sort_values(by='features_importance', ascending=False).head(n_top_feats), x='features_importance', y='features');
#             plt.title(f'{n_top_feats} TOP feature importance');
#             plt.plot()



    #         # Create a SHAP explainer object
    #         explainer = shap.TreeExplainer(cat)
    #         # Calculate SHAP values for the test set
    #         shap_values = explainer.shap_values(X_test )

    #         # Summary Plot to visualize feature importance
    #         shap.summary_plot(shap_values, X_test, feature_names=X.columns, plot_type='bar',max_display=len(X.columns))

            # Alternatively, you can plot a summary plot for a specific instance
            # For example, for the first instance in the test set



            calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
            calibrated_classifier.fit(X_train,y_train)

    #         calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
            # Fold Evaluation

    #         calibrated_classifier.fit(X_train, y_train)
    #         fold_pred   = model.predict_proba(X_test)
            print(50*'**')
            y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
            y_pred = calibrated_classifier.predict(X_test )
    #         y_pred = [1 if i >0.78 else 0 for i in y_pred_prob ]
            print(y_pred_prob , calibrated_classifier.predict_proba(X_test)[:, 1])
            accuracy = accuracy_score(y_test, y_pred)

    #         y_pred = [1 if i >0.55 else 0 for i in y_pred_prob ]
            roc_auc = roc_auc_score(y_test, y_pred_prob)
#             conf_matrix = confusion_matrix(y_test, y_pred)
            loss = roc_auc

#             print(f'Accuracy: {accuracy:.4f}')
#             print(f'ROC AUC: {roc_auc:.4f}')

#             print('\nClassification Report:')
#             print(classification_report(y_test, y_pred))
#             print(f"log_loss validation Fold {i+1}/{5} is   : {loss}" )
            log.append(loss)    
            print(50*'**')
            #update oof


            # Test Evaluation

            test_proba = calibrated_classifier.predict_proba(TEST)

            preds1.append(test_proba)








#             conf_mat  = confusion_matrix(y_test, y_pred) 
#             plt.figure(figsize=(8, 6))
#             sns.set(font_scale=1.2)
#             sns.set_style("whitegrid", {"axes.edgecolor": ".6", "grid.color": ".6"})

#             cmap = sns.color_palette("viridis", as_cmap=True)
#             heatmap = sns.heatmap(conf_matrix, annot=True, fmt='d', cmap=cmap, annot_kws={'size': 14}, cbar=False)

#             heatmap.set_title('Confusion Matrix', fontdict={'fontsize': 16})
#             heatmap.set_xlabel('Predicted', fontdict={'fontsize': 14})
#             heatmap.set_ylabel('True', fontdict={'fontsize': 14})



#             fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
#             roc_auc = auc(fpr, tpr)

#             fig = go.Figure()
#             fig.add_trace(go.Scatter(x=fpr, y=tpr, mode='lines', 
#                                      line=dict(color='#FF4505', width=5),
#                                      name=f'AUC = {roc_auc:.2f}'))

#             fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', 
#                                      line=dict(color='navy', width=2, dash='dash'),
#                                      name='Random'))

#             fig.update_layout(
#                 title='ROC Curve',
#                 xaxis=dict(title='False Positive Rate'),
#                 yaxis=dict(title='True Positive Rate'),
#                 legend=dict(x=0.02, y=0.98),
#                 width=800, height=800
#             )

#             fig.show()

#             threshold = 0.5
#             y_pred_binary = (y_pred_prob > threshold).astype(int)
#             misclassified_indices = np.where(y_pred_binary != y_test)[0]
#             misclassified_indices_per_fold.append(misclassified_indices)


#             fold_predictions_catboost = calibrated_classifier.predict_proba(X_test)[:, 1]

#             # Store the predictions for this fold in the oof_predictions array
#             oof_predictions_catboost[test_index] = fold_predictions_catboost

#             all_features = X.columns.tolist()

#             # Obtenez les noms des fonctionnalités avec une importance nulle dans le modèle CatBoost
#             zero_importance_features = [feature for feature, importance in zip(all_features, cat.feature_importances_) if importance == 0]

#             # Affichez les fonctionnalités avec une importance nulle
#             print("0 importance features :")
#             print(zero_importance_features)

#     plt.show()
    print(50*'##')

    print(f"The overall loss is {np.array(log).mean()}")



#     all_misclassified_indices = np.concatenate(misclassified_indices_per_fold)

#     print("Indices of misclassified instances:")
#     print(all_misclassified_indices)
    return np.array(log).mean(), cat, X_test
In [ ]:
def get_dropped_feature(model, X_test):
    explainer = shap.Explainer(model)
    shap_values = explainer(X_test)
    feature_importance = shap_values.abs.mean(0).values
    importance_df = pd.DataFrame({'features': X_test.columns,
                                  'importance': feature_importance})
    importance_df.sort_values(by='importance', ascending=False, inplace=True)
    return importance_df['features'].iloc[-1]
    
In [ ]:
from tqdm import tqdm
In [ ]:
import shap
In [ ]:
def backward_selection(df, target, max_features=None):
    """
    This function uses the SHAP importance from a catboost model
    to incrementally remove features from the training set until the RMSE no longer improves.
    This function returns the dataframe with the features that give the best RMSE.
    Return at most max_features.
    """
    # get baseline RMSE
    select_df = df.copy()
    total_features = df.shape[1]
    rmse, model, X_test = build_model(select_df, target)
    print(f"{rmse} with {select_df.shape[1]}")
    last_rmse = rmse
    
    # Drop least important feature and recalculate model peformance
    if max_features is None:
        max_features = total_features-1
        
    for num_features in tqdm(range(total_features-1, 1, -1)):
        # Trim features
        dropped_feature = get_dropped_feature(model, X_test)
        tmp_df = select_df.drop(columns=[dropped_feature])

        # Rerun modeling
        rmse, model, X_test = build_model(tmp_df, target)
        print(f"{rmse} with {tmp_df.shape[1]}")
        if (num_features < max_features) and (rmse > last_rmse):
            # RMSE increased, return last dataframe
            return select_df
        else:
            # RMSE improved, continue dropping features
            last_rmse = rmse
            select_df = tmp_df
    return select_df
    
In [ ]:
target = 'DiagPeriodL90D'
reduced_df = backward_selection(train_copy, target, max_features=200)
reduced_df.shape[1]
In [ ]:
train_ext = train_copy[extract_features]
test_ext = test_copy[extract_features]
In [ ]:
train_ext['DiagPeriodL90D'] = train_copy.DiagPeriodL90D
In [ ]:
oof = train_ext[['DiagPeriodL90D']]
folds = Stock.folds
preds1=[]
log = []
X= train_ext.drop('DiagPeriodL90D' , axis=1)
TEST= test_ext
oof_predictions_catboost = np.zeros(len(X))


misclassified_indices_per_fold = []

y = train_ext.DiagPeriodL90D

for j,targ in enumerate(['DiagPeriodL90D']) : 
#     y = train[targ]
    print(50*'--')
    print(f'Training k-Fold Model for Target {targ}')
    print(50*'--')
    for i,( train_index, test_index) in enumerate(folds.split(X, y)):

        print(50*'--')
        print(f'Fold {i+1}/{5}')
        print(50*'--')
        
        X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]
#   class_weights = {0: 0.7 , 1 : 0.3} ,          
      # Train model
#         stock_index.append(X_test.index)
        cat = CatBoostClassifier(random_seed=42 ,early_stopping_rounds=200, cat_features = [i for i in train_ext.columns if train_ext[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,  
                         
                                 logging_level='Silent',
#                                  **{'iterations': 838,
#  'learning_rate': 0.0206258759084974,
#  'depth': 7,
#  'l2_leaf_reg': 8.763527862659274}
                                 
                                 
                            
) 
    
    
        cat.fit(X_train,y_train,eval_set=[(X_train,y_train),(X_test, y_test)], plot= True)
        
        plot_features = pd.DataFrame()
        plot_features['features'] = cat.feature_names_
        plot_features['features_importance'] = cat.feature_importances_
        n_top_feats = 60
        plt.figure(figsize=(16, 16))
        sns.barplot(data=plot_features.sort_values(by='features_importance', ascending=False).head(n_top_feats), x='features_importance', y='features');
        plt.title(f'{n_top_feats} TOP feature importance');
        plt.plot()
       


#         # Create a SHAP explainer object
#         explainer = shap.TreeExplainer(cat)
#         # Calculate SHAP values for the test set
#         shap_values = explainer.shap_values(X_test )

#         # Summary Plot to visualize feature importance
#         shap.summary_plot(shap_values, X_test, feature_names=X.columns, plot_type='bar',max_display=len(X.columns))

        # Alternatively, you can plot a summary plot for a specific instance
        # For example, for the first instance in the test set
        
        
        
        calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        calibrated_classifier.fit(X_train,y_train)
        
#         calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        # Fold Evaluation
        
#         calibrated_classifier.fit(X_train, y_train)
#         fold_pred   = model.predict_proba(X_test)
        print(50*'**')
        y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
        y_pred = calibrated_classifier.predict(X_test )
#         y_pred = [1 if i >0.78 else 0 for i in y_pred_prob ]
        print(y_pred_prob , calibrated_classifier.predict_proba(X_test)[:, 1])
        accuracy = accuracy_score(y_test, y_pred)
        
#         y_pred = [1 if i >0.55 else 0 for i in y_pred_prob ]
        roc_auc = roc_auc_score(y_test, y_pred_prob)
        conf_matrix = confusion_matrix(y_test, y_pred)
        loss = roc_auc

        print(f'Accuracy: {accuracy:.4f}')
        print(f'ROC AUC: {roc_auc:.4f}')

        print('\nClassification Report:')
        print(classification_report(y_test, y_pred))
        print(f"log_loss validation Fold {i+1}/{5} is   : {loss}" )
        log.append(loss)    
        print(50*'**')
        #update oof
        

        # Test Evaluation
        
        test_proba = calibrated_classifier.predict_proba(TEST)

        preds1.append(test_proba)
        
        
        



            
            
        conf_mat  = confusion_matrix(y_test, y_pred) 
        plt.figure(figsize=(8, 6))
        sns.set(font_scale=1.2)
        sns.set_style("whitegrid", {"axes.edgecolor": ".6", "grid.color": ".6"})

        cmap = sns.color_palette("viridis", as_cmap=True)
        heatmap = sns.heatmap(conf_matrix, annot=True, fmt='d', cmap=cmap, annot_kws={'size': 14}, cbar=False)

        heatmap.set_title('Confusion Matrix', fontdict={'fontsize': 16})
        heatmap.set_xlabel('Predicted', fontdict={'fontsize': 14})
        heatmap.set_ylabel('True', fontdict={'fontsize': 14})
        
        
        
        fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
        roc_auc = auc(fpr, tpr)

        fig = go.Figure()
        fig.add_trace(go.Scatter(x=fpr, y=tpr, mode='lines', 
                                 line=dict(color='#FF4505', width=5),
                                 name=f'AUC = {roc_auc:.2f}'))

        fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', 
                                 line=dict(color='navy', width=2, dash='dash'),
                                 name='Random'))

        fig.update_layout(
            title='ROC Curve',
            xaxis=dict(title='False Positive Rate'),
            yaxis=dict(title='True Positive Rate'),
            legend=dict(x=0.02, y=0.98),
            width=800, height=800
        )

        fig.show()
        
        threshold = 0.5
        y_pred_binary = (y_pred_prob > threshold).astype(int)
        misclassified_indices = np.where(y_pred_binary != y_test)[0]
        misclassified_indices_per_fold.append(misclassified_indices)
        
        
        fold_predictions_catboost = calibrated_classifier.predict_proba(X_test)[:, 1]

        # Store the predictions for this fold in the oof_predictions array
        oof_predictions_catboost[test_index] = fold_predictions_catboost

        all_features = X.columns.tolist()

        # Obtenez les noms des fonctionnalités avec une importance nulle dans le modèle CatBoost
        zero_importance_features = [feature for feature, importance in zip(all_features, cat.feature_importances_) if importance == 0]

        # Affichez les fonctionnalités avec une importance nulle
        print("0 importance features :")
        print(zero_importance_features)
        
plt.show()
print(50*'##')

print(f"The overall loss is {np.array(log).mean()}")



all_misclassified_indices = np.concatenate(misclassified_indices_per_fold)

print("Indices of misclassified instances:")
print(all_misclassified_indices) 
In [ ]:
train_copy.num_quadrants.value_counts()
In [ ]:
train_copy.head()
In [ ]:
train_copy['nnn'] =train_copy['ICD10'].astype(int)+train_copy['num_quadrants'].astype(int)
test_copy['nnn'] =test_copy['ICD10'].astype(int)+test_copy['num_quadrants'].astype(int)
In [ ]:
def FE10(df) :

    df['is_upper_outer_quadrant'] = df['Place'].apply(lambda x: 1 if 'upper-outer quadrant' in x else 0)
    df['is_central_portion'] = df['Place'].apply(lambda x: 1 if 'central portion' in x else 0)
    df['is_upper_inner_quadrant'] = df['Place'].apply(lambda x: 1 if 'upper-inner quadrant' in x else 0)
    df['is_lower_outer_quadrant'] = df['Place'].apply(lambda x: 1 if 'lower-outer quadrant' in x else 0)
    df['is_lower_inner_quadrant'] = df['Place'].apply(lambda x: 1 if 'lower-inner quadrant' in x else 0)

    df['is_unspecified_site'] = df['Place'].apply(lambda x: 1 if 'breast of unspecified site' in x else 0)
    df['is_nipple_and_areola'] = df['Place'].apply(lambda x: 1 if 'nipple and areola' in x else 0)
    df['is_axillary_tail'] = df['Place'].apply(lambda x: 1 if 'axillary tail' in x else 0)
    df['is_overlapping_sites'] = df['Place'].apply(lambda x: 1 if 'overlapping sites' in x else 0)

    df['has_axillary_tail'] = df['Place'].apply(lambda x: 1 if 'axillary tail' in x else 0)
    df['has_nipple_and_areola'] = df['Place'].apply(lambda x: 1 if 'nipple and areola' in x else 0)

    df['is_overlapping'] = df['Place'].apply(lambda x: 1 if 'overlapping sites' in x else 0)

    # Count of quadrants involved
    df['num_quadrants'] = df[['is_upper_outer_quadrant', 'is_central_portion', 'is_upper_inner_quadrant',
                               'is_lower_outer_quadrant', 'is_lower_inner_quadrant']].sum(axis=1)

    # Location description
    


    df['breast_location_length'] = df['Place'].apply(lambda x: len(x.split()))

    # Presence of hyphen
    df['has_hyphen'] = df['Place'].apply(lambda x: 1 if '-' in x else 0)

    # Count of specific keywords
    keywords_to_count = ['quadrant', 'portion', 'axillary', 'overlapping']
    for keyword in keywords_to_count:
        df[f'count_of_{keyword}_keywords'] = df['Place'].apply(lambda x: x.lower().count(keyword))

  
    
    return df

train_copy = FE10(train_copy)
test_copy = FE10(test_copy)
In [ ]:
# add_icd = ['is_upper_outer_quadrant','is_central_portion','is_upper_inner_quadrant','is_lower_outer_quadrant','is_lower_inner_quadrant',
# 'is_unspecified_site','is_nipple_and_areola','is_axillary_tail','is_overlapping_sites','has_axillary_tail','has_nipple_and_areola' ,
# 'is_overlapping' ,'num_quadrants' ,'breast_location_length','has_hyphen']

# for col in add_icd : 
#     train_copy[col] = train_copy["ICD10"].astype(str)+"_"+train_copy[col].astype(str)
#     test_copy[col] = test_copy["ICD10"].astype(str)+"_"+test_copy[col].astype(str)
In [ ]:
contingency_table = pd.crosstab(train_copy['nnn'], train_copy['DiagPeriodL90D'])
In [ ]:
contingency_table
In [ ]:
train_copy['ICD10_Place_AgeCat'] = train_copy['ICD10'].astype(str)+(train_copy['bmi']//10).astype(str)+train_copy['Place'].astype(str)
test_copy['ICD10_Place_AgeCat'] = test_copy['ICD10'].astype(str)+(test_copy['bmi']//10).astype(str)+test_copy['Place'].astype(str)
In [ ]:
train_copy.shape
In [ ]:
 
In [ ]:
##############################################################################
In [ ]:
import sys
In [ ]:
X_train , X_test ,y_train , y_test = train_test_split(X, y , test_size=0.2 , random_state=42)
In [ ]:
from catboost import CatBoostRegressor, Pool, EShapCalcType, EFeaturesSelectionAlgorithm
In [ ]:
cat.select_features(
                X_train,
                y=y_train,
                eval_set=[(X_test, y_test)],
                features_for_select=X.columns,
                num_features_to_select=200,
                algorithm=EFeaturesSelectionAlgorithm.RecursiveByShapValues,
                steps=200,
                shap_calc_type="Exact",
                train_final_model=False,
#                 verbose=True,
                logging_level="Silent" ,
                plot=True,
                log_cout=sys.stdout,
                log_cerr=sys.stderr,)
In [ ]:
train_copy2 = train_copy.drop(list(final_set) , axis=1)

test_copy2 = test_copy.drop(list(final_set) , axis=1)
In [ ]:
oof = train_copy2[['DiagPeriodL90D']]
folds = Stock.folds
preds1=[]
log = []
X= train_copy2.drop('DiagPeriodL90D' , axis=1)
TEST= test_copy2
oof_predictions_catboost = np.zeros(len(X))


misclassified_indices_per_fold = []

y = train_copy2.DiagPeriodL90D

for j,targ in enumerate(['DiagPeriodL90D']) : 
#     y = train[targ]
    print(50*'--')
    print(f'Training k-Fold Model for Target {targ}')
    print(50*'--')
    for i,( train_index, test_index) in enumerate(folds.split(X, y)):

        print(50*'--')
        print(f'Fold {i+1}/{5}')
        print(50*'--')
        
        X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]
#   class_weights = {0: 0.7 , 1 : 0.3} ,          
      # Train model
#         stock_index.append(X_test.index)
        cat = CatBoostClassifier(random_seed=42 ,early_stopping_rounds=200, cat_features = [i for i in train_copy2.columns if train_copy2[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,  
                         
                                 logging_level='Silent',**{'iterations': 838,
 'learning_rate': 0.0206258759084974,
 'depth': 7,
 'l2_leaf_reg': 8.763527862659274}
                                 
                                 
                            
) 
    
    
        cat.fit(X_train,y_train,eval_set=[(X_train,y_train),(X_test, y_test)], plot= True)
        
        plot_features = pd.DataFrame()
        plot_features['features'] = cat.feature_names_
        plot_features['features_importance'] = cat.feature_importances_
        n_top_feats = 60
        plt.figure(figsize=(16, 16))
        sns.barplot(data=plot_features.sort_values(by='features_importance', ascending=False).head(n_top_feats), x='features_importance', y='features');
        plt.title(f'{n_top_feats} TOP feature importance');
        plt.plot()
       


#         # Create a SHAP explainer object
#         explainer = shap.TreeExplainer(cat)
#         # Calculate SHAP values for the test set
#         shap_values = explainer.shap_values(X_test )

#         # Summary Plot to visualize feature importance
#         shap.summary_plot(shap_values, X_test, feature_names=X.columns, plot_type='bar',max_display=len(X.columns))

        # Alternatively, you can plot a summary plot for a specific instance
        # For example, for the first instance in the test set
        
        
        
        calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        calibrated_classifier.fit(X_train,y_train)
        
#         calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        # Fold Evaluation
        
#         calibrated_classifier.fit(X_train, y_train)
#         fold_pred   = model.predict_proba(X_test)
        print(50*'**')
        y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
        y_pred = calibrated_classifier.predict(X_test )
#         y_pred = [1 if i >0.78 else 0 for i in y_pred_prob ]
        print(y_pred_prob , calibrated_classifier.predict_proba(X_test)[:, 1])
        accuracy = accuracy_score(y_test, y_pred)
        
#         y_pred = [1 if i >0.55 else 0 for i in y_pred_prob ]
        roc_auc = roc_auc_score(y_test, y_pred_prob)
        conf_matrix = confusion_matrix(y_test, y_pred)
        loss = roc_auc

        print(f'Accuracy: {accuracy:.4f}')
        print(f'ROC AUC: {roc_auc:.4f}')

        print('\nClassification Report:')
        print(classification_report(y_test, y_pred))
        print(f"log_loss validation Fold {i+1}/{5} is   : {loss}" )
        log.append(loss)    
        print(50*'**')
        #update oof
        

        # Test Evaluation
        
        test_proba = calibrated_classifier.predict_proba(TEST)

        preds1.append(test_proba)
        
        
        



            
            
        conf_mat  = confusion_matrix(y_test, y_pred) 
        plt.figure(figsize=(8, 6))
        sns.set(font_scale=1.2)
        sns.set_style("whitegrid", {"axes.edgecolor": ".6", "grid.color": ".6"})

        cmap = sns.color_palette("viridis", as_cmap=True)
        heatmap = sns.heatmap(conf_matrix, annot=True, fmt='d', cmap=cmap, annot_kws={'size': 14}, cbar=False)

        heatmap.set_title('Confusion Matrix', fontdict={'fontsize': 16})
        heatmap.set_xlabel('Predicted', fontdict={'fontsize': 14})
        heatmap.set_ylabel('True', fontdict={'fontsize': 14})
        
        
        
        fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
        roc_auc = auc(fpr, tpr)

        fig = go.Figure()
        fig.add_trace(go.Scatter(x=fpr, y=tpr, mode='lines', 
                                 line=dict(color='#FF4505', width=5),
                                 name=f'AUC = {roc_auc:.2f}'))

        fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', 
                                 line=dict(color='navy', width=2, dash='dash'),
                                 name='Random'))

        fig.update_layout(
            title='ROC Curve',
            xaxis=dict(title='False Positive Rate'),
            yaxis=dict(title='True Positive Rate'),
            legend=dict(x=0.02, y=0.98),
            width=800, height=800
        )

        fig.show()
        
        threshold = 0.5
        y_pred_binary = (y_pred_prob > threshold).astype(int)
        misclassified_indices = np.where(y_pred_binary != y_test)[0]
        misclassified_indices_per_fold.append(misclassified_indices)
        
        
        fold_predictions_catboost = calibrated_classifier.predict_proba(X_test)[:, 1]

        # Store the predictions for this fold in the oof_predictions array
        oof_predictions_catboost[test_index] = fold_predictions_catboost


plt.show()
print(50*'##')
print(f"The overall loss is {np.array(log).mean()}")



all_misclassified_indices = np.concatenate(misclassified_indices_per_fold)

print("Indices of misclassified instances:")
print(all_misclassified_indices) 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
# y = train_copy['DiagPeriodL90D']

# # Set the number of splits
# n_splits = 5

# # Initialize StratifiedKFold without shuffle
# stratified_kfold = StratifiedKFold(n_splits=n_splits)

# # Get the indices for each fold
# fold_indices = list(stratified_kfold.split(X, y))

# # Manually change the order of fold 2 and fold 5
# fold_indices[1], fold_indices[4] = fold_indices[4], fold_indices[1]

# oof_predictions_catboost = np.zeros(len(X))
# misclassified_indices_per_fold = []

# for i, (train_index, test_index) in enumerate(fold_indices):
#     print(50*'--')
#     print(f'Fold {i+1}/{n_splits}')
#     print(50*'--')

#     X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]

#     cat = CatBoostClassifier(random_seed=42, early_stopping_rounds=200, cat_features=[i for i in train_copy.columns if train_copy[i].dtype == 'object'] + ["patient_zip3"], 
#                              loss_function="Logloss", use_best_model=True, eval_metric="AUC", 
#                              text_features=['breast_cancer_diagnosis_desc'], logging_level='Silent')

#     cat.fit(X_train, y_train, eval_set=[(X_train, y_train), (X_test, y_test)], plot=True)
#     calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit')
#     calibrated_classifier.fit(X_train, y_train)

#     y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
#     y_pred = calibrated_classifier.predict(X_test)

#     accuracy = accuracy_score(y_test, y_pred)
#     roc_auc = roc_auc_score(y_test, y_pred_prob)
#     conf_matrix = confusion_matrix(y_test, y_pred)
#     loss = roc_auc

#     print(f'Accuracy: {accuracy:.4f}')
#     print(f'ROC AUC: {roc_auc:.4f}')
#     print('\nClassification Report:')
#     print(classification_report(y_test, y_pred))
#     print(f"log_loss validation Fold {i+1}/{n_splits} is: {loss}")
#     print(50*'**')

#     # Update oof
#     oof_predictions_catboost[test_index] = calibrated_classifier.predict_proba(X_test)[:, 1]

#     # Test Evaluation
#     test_proba = calibrated_classifier.predict_proba(TEST)
#     preds1.append(test_proba)

#     # Plot confusion matrix and ROC curve
#     # ... (your plotting code)

#     # Calculate misclassified indices
#     threshold = 0.5
#     y_pred_binary = (y_pred_prob > threshold).astype(int)
#     misclassified_indices = np.where(y_pred_binary != y_test)[0]
#     misclassified_indices_per_fold.append(misclassified_indices)

# plt.show()
# print(50*'##')
# print(f"The overall loss is {np.array(log).mean()}")

# all_misclassified_indices = np.concatenate(misclassified_indices_per_fold)
# print("Indices of misclassified instances:")
# print(all_misclassified_indices)
In [ ]:
X= train_copy.drop('DiagPeriodL90D' , axis=1)


y = train_copy.DiagPeriodL90D
In [ ]:
from lofo import LOFOImportance, Dataset, plot_importance
In [ ]:
# dataset = Dataset(df=train_copy, target="DiagPeriodL90D", features=[col for col in train_copy.columns if col != "DiagPeriodL90D"])

# # Split the data into training and testing sets
# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# # Define a CatBoost model
# model = CatBoostClassifier(random_seed=42 ,early_stopping_rounds=200, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3"]+["payer_type"], 
#                                  loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
#                                 text_features = ['breast_cancer_diagnosis_desc'] ,  
                         
#                                  logging_level='Silent'
# ) 

# # Use LOFOImportance for feature importance analysis
# lofo_imp = LOFOImportance(dataset, model=model, cv=4, scoring="roc_auc")

# # Get feature importance
# feature_importance = lofo_imp.get_importance()

# # Plot the results
# plot_importance(feature_importance, figsize=(12, 8))
In [ ]:
**{'iterations': 501, 'learning_rate': 0.01862041400994075, 'depth': 7}
In [ ]:
# import phik
# from phik.report import plot_correlation_matrix

# sampled_data = train_copy2.sample(frac=0.1, random_state=42)  # Adjust the fraction as needed

# corr_matrix = sampled_data.phik_matrix()
In [ ]:
# train_copy2 = train_copy.copy(deep =True)
# train_copy2["unknown"] = train_copy2['new_feature15']+train_copy2['new_feature3']
# feature1 = 'new_feature15'  # Replace 'your_feature1' with the actual name of your first feature
# feature2 = 'DiagPeriodL90D'  # Replace 'your_feature2' with the actual name of your second feature

# # Extract the two features as numpy arrays
# array1 = train_copy2[feature1].values
# array2 = train_copy2[feature2].values

# # Calculate the phi-k correlation between the two features
# phi_k_corr = phik.phik_from_array(array1, array2)

# print(f"Phi-k correlation between {feature1} and {feature2}: {phi_k_corr:.4f}")
In [ ]:
# for i,j in zip(corr_matrix.loc['DiagPeriodL90D'].index , corr_matrix.loc['DiagPeriodL90D'].values) : 
#     print(f"{i} ==> {j}")
In [ ]:
# import phik
# from itertools import combinations

# train_copy2 = train_copy.copy(deep =True)
# # Assuming train_copy is your DataFrame
# features = train_copy2.columns

# # Create an empty dictionary to store phi-k correlations
# phi_k_correlations = {}

# # Iterate through all combinations of two features
# for feature1, feature2 in combinations(features, 2):
#     # Extract the two features as numpy arrays
#     if feature1!="DiagPeriodL90D" :
#         if feature2!="DiagPeriodL90D" :
#             train_copy2['new'] = train_copy2[feature1].astype(str)+'_'+train_copy2[feature2].astype(str)
#             array1 = train_copy2['new'].values
#             array2 = train_copy2["DiagPeriodL90D"].values

#             # Calculate the phi-k correlation between the two features
#             phi_k_corr = phik.phik_from_array(array1, array2)

#             # Store the result in the dictionary
#             phi_k_correlations[(feature1, feature2)] = phi_k_corr
#             print((feature1, feature2) , phi_k_corr)
# # Print phi-k correlations for all combinations
# for (feature1, feature2), phi_k_corr in phi_k_correlations.items():
#     print(f"Phi-k correlation between {feature1} and {feature2}: {phi_k_corr:.4f}")
In [ ]:
import phik
from itertools import combinations
from termcolor import colored



train_copy2 = train_copy.copy(deep=True)

# Assuming train_copy is your DataFrame
features = train_copy2.columns

# Create an empty dictionary to store phi-k correlations
phi_k_correlations = {}

# Define thresholds for color highlighting
threshold_green = 0.7
threshold_gold = 0.8

for feature1, feature2 in combinations(features, 2):
    if feature1 != "DiagPeriodL90D":
        if feature2 != "DiagPeriodL90D":
            train_copy2['new'] = train_copy2[feature1].astype(str) + '_' + train_copy2[feature2].astype(str)
            array1 = train_copy2['new'].values
            array2 = train_copy2["DiagPeriodL90D"].values

            phi_k_corr = phik.phik_from_array(array1, array2)

            phi_k_correlations[(feature1, feature2)] = phi_k_corr

            if phi_k_corr >= threshold_gold:
                color = 'yellow'
            elif phi_k_corr >= threshold_green:
                color = 'green'
            else:
                color = 'white'

            print(colored((feature1, feature2), color), colored(phi_k_corr, color))

for (feature1, feature2), phi_k_corr in phi_k_correlations.items():
    if phi_k_corr >= threshold_gold:
        color = 'yellow'
    elif phi_k_corr >= threshold_green:
        color = 'green'
    else:
        color = 'white'

    print(colored(f"Phi-k correlation between {feature1} and {feature2}: {phi_k_corr:.4f}", color))
In [ ]:
final_dict = dict()

for new_feat in phi_k_correlations.keys():
    if phi_k_correlations[new_feat]>=0.7959646985988071 : 
        final_dict[new_feat] = phi_k_correlations[new_feat]
In [ ]:
train_copy_last = train_copy.copy(deep =True)
test_copy_last = test_copy.copy(deep =True)
In [ ]:
train_copy7
In [ ]:
d2 =  {('payer_type', 'ICD10'): 0.7974115325053814,
 ('Left', 'new_feature2'): 0.796393858292148,
 ('Left', 'new_feature3'): 0.7959646985988071,
 ('Left', 'new_feature5'): 0.7959647242442798,
 ('Left', 'new_feature15'): 0.795996487789025,
 ('Right', 'new_feature2'): 0.7965542110808593,
 ('Right', 'new_feature3'): 0.7960222719192501,
 ('Right', 'new_feature5'): 0.796012780984905,
 ('Right', 'new_feature15'): 0.7961223982570049,
 ('ICD10', 'male_patient'): 0.8081651407184726,
 ('ICD10', 'density_3'): 0.7961243262211823,
 ('ICD10', 'age_median_3'): 0.7960194907153129,
 ('ICD10', 'age_under_10_3'): 0.7960983111473753,
 ('ICD10', 'age_10_to_19_3'): 0.7959989028195832,
 ('ICD10', 'age_30s_3'): 0.7960432260073103,
 ('ICD10', 'age_60s_3'): 0.7960127171801115,
 ('ICD10', 'divorced_3'): 0.7960550853218871,
 ('ICD10', 'family_size_3'): 0.7964252591191021,
 ('ICD10', 'income_household_under_5_3'): 0.7964822885351781,
 ('ICD10', 'income_household_20_to_25_3'): 0.7963164732131581,
 ('ICD10', 'income_household_100_to_150_3'): 0.796296916108168,
 ('ICD10', 'income_individual_median_3'): 0.7962622866724125,
 ('ICD10', 'education_graduate_3'): 0.7961897979218501,
 ('ICD10', 'self_employed_3'): 0.7961244037510928,
 ('ICD10', 'race_white_3'): 0.7967566142661975,
 ('ICD10', 'race_black_3'): 0.7965716409630559,
 ('ICD10', 'race_native_3'): 0.7961114473172778,
 ('ICD10', 'disabled_3'): 0.7962140054034981,
 ('ICD10', 'poverty_3'): 0.7966889317492131,
 ('ICD10', 'limited_english_3'): 0.7963969822439823,
 ('ICD10', 'commute_time_3'): 0.7962924826102122,
 ('ICD10', 'extract_metastatic1'): 0.7963532957846157,
 ('ICD10', 'retirement'): 0.8096642902246678,
 ('ICD10', 'CA_neighbor'): 0.8080942473499293,
 ('ICD10', 'TX_neighbor'): 0.8080592458303844,
 ('ICD10', 'ID_neighbor'): 0.8080365922314948,
 ('ICD10', 'NY_neighbor'): 0.808151955393448,
 ('ICD10', 'IL_neighbor'): 0.8081025398027346,
 ('ICD10', 'MI_neighbor'): 0.8081556127200781,
 ('ICD10', 'OR_neighbor'): 0.8081501768393876,
 ('ICD10', 'MT_neighbor'): 0.8081214390724804,
 ('ICD10', 'KY_neighbor'): 0.8081768128646157,
 ('ICD10', 'OH_neighbor'): 0.8081422481359904,
 ('ICD10', 'IN_neighbor'): 0.8080706258035805,
 ('ICD10', 'FL_neighbor'): 0.8081594841264915,
 ('ICD10', 'CO_neighbor'): 0.808145311486847,
 ('ICD10', 'GA_neighbor'): 0.8081948936547552,
 ('ICD10', 'VA_neighbor'): 0.808034616597261,
 ('ICD10', 'MD_neighbor'): 0.8084923658180818,
 ('ICD10', 'KS_neighbor'): 0.8084955444393266,
 ('ICD10', 'WI_neighbor'): 0.8082277532420888,
 ('ICD10', 'PA_neighbor'): 0.8081510607873259,
 ('ICD10', 'NM_neighbor'): 0.8080876320818899,
 ('ICD10', 'WA_neighbor'): 0.8082414249694383,
 ('ICD10', 'MN_neighbor'): 0.8080765276884089,
 ('ICD10', 'NC_neighbor'): 0.8083809818115376,
 ('ICD10', 'AL_neighbor'): 0.8080931317687369,
 ('ICD10', 'SC_neighbor'): 0.8081023485300675,
 ('ICD10', 'LA_neighbor'): 0.8084138503914293,
 ('ICD10', 'IA_neighbor'): 0.8082185526366211,
 ('ICD10', 'TN_neighbor'): 0.8082804621884518,
 ('ICD10', 'NE_neighbor'): 0.8085293395679389,
 ('ICD10', 'AZ_neighbor'): 0.8083382104588747,
 ('ICD10', 'MO_neighbor'): 0.8084256114867833,
 ('ICD10', 'NV_neighbor'): 0.8082055279452391,
 ('ICD10', 'SD_neighbor'): 0.8084176028120621,
 ('ICD10', 'DC_neighbor'): 0.8084079403751846,
 ('ICD10', 'AR_neighbor'): 0.8081904029731143,
 ('ICD10', 'UT_neighbor'): 0.808200352566604,
 ('ICD10', 'WV_neighbor'): 0.808185279587891,
 ('ICD10', 'ND_neighbor'): 0.8085247440352225,
 ('ICD10', 'OK_neighbor'): 0.8080254728439576,
 ('ICD10', 'WY_neighbor'): 0.8087136725810676,
 ('ICD10', 'DE_neighbor'): 0.808151308854838,
 ('ICD10', 'NJ_neighbor'): 0.8081248497830769,
 ('ICD10', 'MS_neighbor'): 0.8080343736838982,
 ('ICD10', 'CT_neighbor'): 0.8080600802508389,
 ('ICD10', 'MA_neighbor'): 0.8080600802508389,
 ('ICD10', 'new_feature2'): 0.8084256114867833,
 ('ICD10', 'new_feature3'): 0.8080365922314948,
 ('ICD10', 'new_feature5'): 0.808034616597261,
 ('ICD10', 'new_feature8'): 0.7964822885351781,
 ('ICD10', 'new_feature15'): 0.8080600802508389,
 ('income_household_under_5_3', 'new_feature8'): 0.796482288535178,
 ('Allconbin', 'ICD10_patient_age_payer_type'): 0.7988272014158029,
 ('CA_neighbor', 'new_feature2'): 0.7964924680227914,
 ('CA_neighbor', 'new_feature5'): 0.7960443682069124,
 ('CA_neighbor', 'new_feature15'): 0.7960748803873094,
 ('TX_neighbor', 'new_feature3'): 0.7960065291166047,
 ('TX_neighbor', 'new_feature5'): 0.7960089277091832,
 ('TX_neighbor', 'new_feature15'): 0.796039149434738,
 ('ID_neighbor', 'new_feature2'): 0.7964277802969393,
 ('ID_neighbor', 'new_feature3'): 0.8080365922314948,
 ('ID_neighbor', 'new_feature5'): 0.7959798703874963,
 ('ID_neighbor', 'new_feature15'): 0.7960076955522748,
 ('NY_neighbor', 'new_feature2'): 0.7965634774349653,
 ('NY_neighbor', 'new_feature3'): 0.7961138009097439,
 ('NY_neighbor', 'new_feature5'): 0.7961080145670978,
 ('NY_neighbor', 'new_feature15'): 0.7961399203843749,
 ('IL_neighbor', 'new_feature3'): 0.7960523070699675,
 ('IL_neighbor', 'new_feature15'): 0.7960835008400944,
 ('MI_neighbor', 'new_feature2'): 0.7964983568811805,
 ('MI_neighbor', 'new_feature3'): 0.796108850330623,
 ('MI_neighbor', 'new_feature5'): 0.7961180178250309,
 ('MI_neighbor', 'new_feature15'): 0.7961456354607557,
 ('OR_neighbor', 'new_feature2'): 0.7965672961523255,
      }

for new_feat in final_dict : 
    print("#"*50)
    print(f"adding {new_feat} .....")
    
    
    train_copy[f"{new_feat[0]}_{new_feat[1]}"] = train_copy[f"{new_feat[0]}"].astype(str)+"_"+train_copy[f"{new_feat[0]}"].astype(str)
    test_copy[f"{new_feat[0]}_{new_feat[1]}"] = test_copy[f"{new_feat[0]}"].astype(str)+"_"+test_copy[f"{new_feat[0]}"].astype(str)
    print(i)
In [ ]:
train_copy7 = train_copy_last.copy(deep =True)
test_copy7 = test_copy_last.copy(deep =True)
max_score = 0.8099246010824646
i = 1
for new_feat in final_dict : 
    print("#"*50)
    print(f"adding {new_feat} .....")
    
    
    train_copy7[f"{new_feat[0]}_{new_feat[1]}"] = train_copy7[f"{new_feat[0]}"].astype(str)+"_"+train_copy7[f"{new_feat[0]}"].astype(str)
    test_copy7[f"{new_feat[0]}_{new_feat[1]}"] = test_copy7[f"{new_feat[0]}"].astype(str)+"_"+test_copy7[f"{new_feat[0]}"].astype(str)
    print(i)
    
    i+= 1
    score1 = score(train_copy7, test_copy7)

    if score1 > max_score:
        print(f'Hey Aymen, we improved to {score1}')
        max_score = score1
    else:
        train_copy7 = drop_column(train_copy7, f"{new_feat[0]}_{new_feat[1]}")
        test_copy7 = drop_column(test_copy7, f"{new_feat[0]}_{new_feat[1]}")
    
In [ ]:
final_dict
In [ ]:
 
In [ ]:
 
In [ ]:
Phi-k correlation between MA_neighbor and new_feature15: 0.8081
Phi-k correlation between CT_neighbor and new_feature15: 0.8081
Phi-k correlation between MO_neighbor and new_feature2: 0.8084
In [ ]:
plot_correlation_matrix(corr_matrix.values , 
                       x_labels = corr_matrix.columns , 
                       y_labels = corr_matrix.index , 
                       vmin = 0 , 
                       vmax = 1 , 
                       color_map = 'Blues'
                       ,)
In [ ]:
# model = cat = CatBoostClassifier(random_seed=42 ,early_stopping_rounds=200, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3"], 
#                                  loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
#                                 text_features = ['breast_cancer_diagnosis_desc'] ,  
                         
#                                  logging_level='Silent',**{'iterations': 501, 'learning_rate': 0.01862041400994075, 'depth': 7}
# ).fit(X_train,y_train)
# roc_auc_score(y_test, model.predict_proba(X_test))    
In [ ]:
 
In [ ]:
##########################################################
to_drop = list()

# Iterating over rows starting from the second one, because position [0, 0] will be self-correlation which is 1
for i in range(1, len(corr_matrix)):
    # Iterating over columns of the row. Only going under the diagonal.
    for j in range(i):
        # See if the correlation between two features are more than a selected threshold
        if corr_matrix.iloc[i, j] >= 0.98:
            # Then keep the one from thos two which correlates with target better
            if abs(pd.concat([X[corr_matrix.index[i]], y], axis=1).corr().iloc[0][1]) > abs(pd.concat([X[corr_matrix.columns[j]], y], axis=1).corr().iloc[0][1]):
                to_drop.append(corr_matrix.columns[j])
            else:
                to_drop.append(corr_matrix.index[i])

to_drop = list(set(to_drop))

#############################################################
In [ ]:
 
In [ ]:
The overall loss is 0.8102420954765839 5*1
The overall loss is 0.81058461411717 10*1
In [ ]:
X= train_copy.drop('DiagPeriodL90D' , axis=1)

initial_lr = 0.2
decay_rate = 0.01


oof_predictions_catboost = np.zeros(len(X))
misclassified_indices_per_fold = []

y = train_copy.DiagPeriodL90D

for j, targ in enumerate(['DiagPeriodL90D']):
    print(50*'--')
    print(f'Training k-Fold Model for Target {targ}')
    print(50*'--')
    for i, (train_index, test_index) in enumerate(folds.split(X, y)):
        print(50*'--')
        print(f'Fold {i+1}/{5}')
        print(50*'--')

        X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]

        # Calculate the current learning rate based on the annealing schedule
        current_lr = initial_lr / (1 + decay_rate * (j * folds.n_splits + i))

        # Train model with the current learning rate
        cat = CatBoostClassifier(
            random_seed=42,
            early_stopping_rounds=200,
            cat_features=[i for i in train_copy.columns if train_copy[i].dtype == 'object'] + ["patient_zip3"],
            loss_function="Logloss",
            use_best_model=True,
            eval_metric="AUC",
            text_features=['breast_cancer_diagnosis_desc'],
            logging_level='Silent',
            iterations=501,
            learning_rate=current_lr,
            depth=7
        )

        cat.fit(X_train, y_train, eval_set=[(X_train, y_train), (X_test, y_test)], plot=True)

        calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit')
        calibrated_classifier.fit(X_train, y_train)

        y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
        y_pred = calibrated_classifier.predict(X_test)
        accuracy = accuracy_score(y_test, y_pred)
        roc_auc = roc_auc_score(y_test, y_pred_prob)
        conf_matrix = confusion_matrix(y_test, y_pred)
        loss = roc_auc

        print(f'Accuracy: {accuracy:.4f}')
        print(f'ROC AUC: {roc_auc:.4f}')

        print('\nClassification Report:')
        print(classification_report(y_test, y_pred))
        print(f"log_loss validation Fold {i+1}/{5} is   : {loss}" )

        misclassified_indices = np.where(y_pred != y_test)[0]
        misclassified_indices_per_fold.append(misclassified_indices)

        fold_predictions_catboost = calibrated_classifier.predict_proba(X_test)[:, 1]
        oof_predictions_catboost[test_index] = fold_predictions_catboost

plt.show()
print(50*'##')
print(f"The overall loss is {np.array(log).mean()}")
In [ ]:
welcome back
In [ ]:
len(oof_predictions_catboost)
In [ ]:
cat_train_pred = pd.DataFrame()
cat_train_pred['pred'] = oof_predictions_catboost
cat_train_pred.to_csv('cat_train_pred.csv' , index= False)
In [ ]:
#<###################""
In [ ]:
train_copy3 = train_copy.copy(deep =True)
test_copy3 = test_copy.copy(deep =True)
lgb_train_pred = pd.read_csv('lgb_train_pred.csv')
cat_train_pred = pd.read_csv('cat_train_pred.csv')
In [ ]:
train_copy3['pred'] = cat_train_pred.pred.values
test_copy3['pred'] = sub.DiagPeriodL90D.values
In [ ]:
oof = train_copy[['DiagPeriodL90D']]
folds = Stock.folds
preds1=[]
log = []
X= train_copy.drop('DiagPeriodL90D' , axis=1)
TEST= test_copy
oof_predictions_catboost = np.zeros(len(X))


misclassified_indices_per_fold = []

y = train_copy.DiagPeriodL90D

for j,targ in enumerate(['DiagPeriodL90D']) : 
#     y = train[targ]
    print(50*'--')
    print(f'Training k-Fold Model for Target {targ}')
    print(50*'--')
    for i,( train_index, test_index) in enumerate(folds.split(X, y)):

        print(50*'--')
        print(f'Fold {i+1}/{5}')
        print(50*'--')
        
        X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]
#   class_weights = {0: 0.7 , 1 : 0.3} ,          
      # Train model
#         stock_index.append(X_test.index)
        cat = CatBoostClassifier(random_seed=42 ,early_stopping_rounds=200, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,  
                         
                                 logging_level='Silent'
) 
    
    
        cat.fit(X_train,y_train,eval_set=[(X_train,y_train),(X_test, y_test)], plot= True)
        
        
        plot_features = pd.DataFrame()
        plot_features['features'] = cat.feature_names_
        plot_features['features_importance'] = cat.feature_importances_
        n_top_feats = 60
        plt.figure(figsize=(16, 16))
        sns.barplot(data=plot_features.sort_values(by='features_importance', ascending=False).head(n_top_feats), x='features_importance', y='features');
        plt.title(f'{n_top_feats} TOP feature importance');
        plt.plot()
       


#         # Create a SHAP explainer object
#         explainer = shap.TreeExplainer(cat)
#         # Calculate SHAP values for the test set
#         shap_values = explainer.shap_values(X_test )

#         # Summary Plot to visualize feature importance
#         shap.summary_plot(shap_values, X_test, feature_names=X.columns, plot_type='bar',max_display=len(X.columns))

        # Alternatively, you can plot a summary plot for a specific instance
        # For example, for the first instance in the test set
        
        
        
        calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        calibrated_classifier.fit(X_train,y_train)
        
#         calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        # Fold Evaluation
        
#         calibrated_classifier.fit(X_train, y_train)
#         fold_pred   = model.predict_proba(X_test)
        print(50*'**')
        y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
        y_pred = calibrated_classifier.predict(X_test )
#         y_pred = [1 if i >0.78 else 0 for i in y_pred_prob ]
        print(y_pred_prob , calibrated_classifier.predict_proba(X_test)[:, 1])
        accuracy = accuracy_score(y_test, y_pred)
        
#         y_pred = [1 if i >0.55 else 0 for i in y_pred_prob ]
        roc_auc = roc_auc_score(y_test, y_pred_prob)
        conf_matrix = confusion_matrix(y_test, y_pred)
        loss = roc_auc

        print(f'Accuracy: {accuracy:.4f}')
        print(f'ROC AUC: {roc_auc:.4f}')

        print('\nClassification Report:')
        print(classification_report(y_test, y_pred))
        print(f"log_loss validation Fold {i+1}/{5} is   : {loss}" )
        log.append(loss)    
        print(50*'**')
        #update oof
        

        # Test Evaluation
        
        test_proba = calibrated_classifier.predict_proba(TEST)

        preds1.append(test_proba)
        
        
        



            
            
        conf_mat  = confusion_matrix(y_test, y_pred) 
        plt.figure(figsize=(8, 6))
        sns.set(font_scale=1.2)
        sns.set_style("whitegrid", {"axes.edgecolor": ".6", "grid.color": ".6"})

        cmap = sns.color_palette("viridis", as_cmap=True)
        heatmap = sns.heatmap(conf_matrix, annot=True, fmt='d', cmap=cmap, annot_kws={'size': 14}, cbar=False)

        heatmap.set_title('Confusion Matrix', fontdict={'fontsize': 16})
        heatmap.set_xlabel('Predicted', fontdict={'fontsize': 14})
        heatmap.set_ylabel('True', fontdict={'fontsize': 14})
        
        
        
        fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
        roc_auc = auc(fpr, tpr)

        fig = go.Figure()
        fig.add_trace(go.Scatter(x=fpr, y=tpr, mode='lines', 
                                 line=dict(color='#FF4505', width=5),
                                 name=f'AUC = {roc_auc:.2f}'))

        fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', 
                                 line=dict(color='navy', width=2, dash='dash'),
                                 name='Random'))

        fig.update_layout(
            title='ROC Curve',
            xaxis=dict(title='False Positive Rate'),
            yaxis=dict(title='True Positive Rate'),
            legend=dict(x=0.02, y=0.98),
            width=800, height=800
        )

        fig.show()
        
        threshold = 0.5
        y_pred_binary = (y_pred_prob > threshold).astype(int)
        misclassified_indices = np.where(y_pred_binary != y_test)[0]
        misclassified_indices_per_fold.append(misclassified_indices)
        
        
        fold_predictions_catboost = calibrated_classifier.predict_proba(X_test)[:, 1]

        # Store the predictions for this fold in the oof_predictions array
        oof_predictions_catboost[test_index] = fold_predictions_catboost


plt.show()
print(50*'##')
print(f"The overall loss is {np.array(log).mean()}")



all_misclassified_indices = np.concatenate(misclassified_indices_per_fold)

print("Indices of misclassified instances:")
print(all_misclassified_indices) 
In [ ]:
misclassified_indices_per_fold
drop_index =list()
for i in misclassified_indices_per_fold :
    for j in i :
        drop_index.append(j)
In [ ]:
len(drop_index)
In [ ]:
train_copy2 = train_copy.drop(drop_index)
In [ ]:
class Stock : 
    n,_ = train.shape
    y = train.DiagPeriodL90D
    n_splits =5
    folds = StratifiedKFold(n_splits = n_splits)
In [ ]:
oof = train_copy2[['DiagPeriodL90D']]
folds = Stock.folds
preds1=[]
log = []
X= train_copy2.drop('DiagPeriodL90D' , axis=1)
TEST= test_copy
oof_predictions_catboost = np.zeros(len(X))


misclassified_indices_per_fold = []

y = train_copy2.DiagPeriodL90D

for j,targ in enumerate(['DiagPeriodL90D']) : 
#     y = train[targ]
    print(50*'--')
    print(f'Training k-Fold Model for Target {targ}')
    print(50*'--')
    for i,( train_index, test_index) in enumerate(folds.split(X, y)):

        print(50*'--')
        print(f'Fold {i+1}/{5}')
        print(50*'--')
        
        X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]
#   class_weights = {0: 0.7 , 1 : 0.3} ,          
      # Train model
#         stock_index.append(X_test.index)
        cat = CatBoostClassifier(random_seed=42 ,early_stopping_rounds=200, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,  
                         
                                 logging_level='Silent'
) 
    
    
        cat.fit(X_train,y_train,eval_set=[(X_train,y_train),(X_test, y_test)], plot= True)
        
        
        plot_features = pd.DataFrame()
        plot_features['features'] = cat.feature_names_
        plot_features['features_importance'] = cat.feature_importances_
        n_top_feats = 60
        plt.figure(figsize=(16, 16))
        sns.barplot(data=plot_features.sort_values(by='features_importance', ascending=False).head(n_top_feats), x='features_importance', y='features');
        plt.title(f'{n_top_feats} TOP feature importance');
        plt.plot()
       


#         # Create a SHAP explainer object
#         explainer = shap.TreeExplainer(cat)
#         # Calculate SHAP values for the test set
#         shap_values = explainer.shap_values(X_test )

#         # Summary Plot to visualize feature importance
#         shap.summary_plot(shap_values, X_test, feature_names=X.columns, plot_type='bar',max_display=len(X.columns))

        # Alternatively, you can plot a summary plot for a specific instance
        # For example, for the first instance in the test set
        
        
        
        calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        calibrated_classifier.fit(X_train,y_train)
        
#         calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        # Fold Evaluation
        
#         calibrated_classifier.fit(X_train, y_train)
#         fold_pred   = model.predict_proba(X_test)
        print(50*'**')
        y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
        y_pred = calibrated_classifier.predict(X_test )
#         y_pred = [1 if i >0.78 else 0 for i in y_pred_prob ]
        print(y_pred_prob , calibrated_classifier.predict_proba(X_test)[:, 1])
        accuracy = accuracy_score(y_test, y_pred)
        
#         y_pred = [1 if i >0.55 else 0 for i in y_pred_prob ]
        roc_auc = roc_auc_score(y_test, y_pred_prob)
        conf_matrix = confusion_matrix(y_test, y_pred)
        loss = roc_auc

        print(f'Accuracy: {accuracy:.4f}')
        print(f'ROC AUC: {roc_auc:.4f}')

        print('\nClassification Report:')
        print(classification_report(y_test, y_pred))
        print(f"log_loss validation Fold {i+1}/{5} is   : {loss}" )
        log.append(loss)    
        print(50*'**')
        #update oof
        

        # Test Evaluation
        
        test_proba = calibrated_classifier.predict_proba(TEST)

        preds1.append(test_proba)
        
        
        



            
            
        conf_mat  = confusion_matrix(y_test, y_pred) 
        plt.figure(figsize=(8, 6))
        sns.set(font_scale=1.2)
        sns.set_style("whitegrid", {"axes.edgecolor": ".6", "grid.color": ".6"})

        cmap = sns.color_palette("viridis", as_cmap=True)
        heatmap = sns.heatmap(conf_matrix, annot=True, fmt='d', cmap=cmap, annot_kws={'size': 14}, cbar=False)

        heatmap.set_title('Confusion Matrix', fontdict={'fontsize': 16})
        heatmap.set_xlabel('Predicted', fontdict={'fontsize': 14})
        heatmap.set_ylabel('True', fontdict={'fontsize': 14})
        
        
        
        fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
        roc_auc = auc(fpr, tpr)

        fig = go.Figure()
        fig.add_trace(go.Scatter(x=fpr, y=tpr, mode='lines', 
                                 line=dict(color='#FF4505', width=5),
                                 name=f'AUC = {roc_auc:.2f}'))

        fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', 
                                 line=dict(color='navy', width=2, dash='dash'),
                                 name='Random'))

        fig.update_layout(
            title='ROC Curve',
            xaxis=dict(title='False Positive Rate'),
            yaxis=dict(title='True Positive Rate'),
            legend=dict(x=0.02, y=0.98),
            width=800, height=800
        )

        fig.show()
        
        threshold = 0.5
        y_pred_binary = (y_pred_prob > threshold).astype(int)
        misclassified_indices = np.where(y_pred_binary != y_test)[0]
        misclassified_indices_per_fold.append(misclassified_indices)
        
        
        fold_predictions_catboost = calibrated_classifier.predict_proba(X_test)[:, 1]

        # Store the predictions for this fold in the oof_predictions array
        oof_predictions_catboost[test_index] = fold_predictions_catboost


plt.show()
print(50*'##')
print(f"The overall loss is {np.array(log).mean()}")



all_misclassified_indices = np.concatenate(misclassified_indices_per_fold)

print("Indices of misclassified instances:")
print(all_misclassified_indices) 
In [ ]:
 
In [ ]:
 
In [ ]:
def specified(df) : 
    df['specified'] = df['breast_cancer_diagnosis_code'].apply(lambda x: 1 if 'specified' in x.lower() else 0)
    return df

train_copy2 = specified(train_copy2)
test_copy2 = specified(test_copy2)
In [ ]:
train
In [ ]:
The overall loss is 0.8099246010824646
In [ ]:
plot_features = pd.DataFrame()
plot_features['features'] = cat.feature_names_
plot_features['features_importance'] = cat.feature_importances_
n_top_feats = 60
plt.figure(figsize=(16, 16))
sns.barplot(data=plot_features.sort_values(by='features_importance', ascending=False).head(n_top_feats), x='features_importance', y='features');
plt.title(f'{n_top_feats} TOP feature importance');
In [ ]:
The overall loss is 0.8079111868715412 +1
The overall loss is 0.8082966899115125 +2
The overall loss is 0.8083719642953394 +3
In [ ]:
The overall loss is 0.8087117697271285  the class value droped (19 feature) LB => 0.81
In [ ]:
till we used 13 The overall loss is 0.8085294157862808 and LB => 0.809
In [ ]:
The overall loss is 0.8071147301835536
In [ ]:
563 406
513 456
568 401
557 412
522 447
In [ ]:
train_copy2 = train_copy.copy(deep =True)
test_copy2 = test_copy.copy(deep =True)
In [ ]:
 
In [ ]:
from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd


from sklearn.feature_extraction.text import CountVectorizer
import pandas as pd

# Sample DataFrame with a text feature
data = {'breast_cancer_diagnosis_desc': [
    'Malignant neoplasm of breast of unspecified site of female breast',
    'Malignant neoplasm of upper-outer quadrant of female breast',
    'Malignant neoplasm of overlapping sites of female breast',
    'Malignant neoplasm of upper-inner quadrant of female breast',
    'Malignant neoplasm of central portion of breast, female breast',
    'Malignant neoplasm of lower-outer quadrant of female breast',
    'Malignant neoplasm of lower-inner quadrant of female breast',
    'Malignant neoplasm of nipple and areola, female breast',
    'Malignant neoplasm of axillary tail of female breast',
    'Malignant neoplasm of breast',
    'Malignant neoplasm of breast of unspecified site of male breast',
    'Malignant neoplasm of nipple and areola, male breast',
    'Malignant neoplasm of upper-outer quadrant of male breast'
]}

df = pd.DataFrame(data)

# Create a Count Vectorizer
count_vectorizer = CountVectorizer()
# Fit and transform the text feature
tfidf_matrix = count_vectorizer.fit_transform(train_copy2['breast_cancer_diagnosis_desc'])
tfidf_matrix2 = count_vectorizer.transform(test_copy2['breast_cancer_diagnosis_desc'])
# Convert the TF-IDF matrix to a DataFrame
tfidf_df = pd.DataFrame(tfidf_matrix.toarray(), columns=tfidf_vectorizer.get_feature_names_out())
tfidf_df2 = pd.DataFrame(tfidf_matrix2.toarray(), columns=tfidf_vectorizer.get_feature_names_out())
# Concatenate the original DataFrame and the TF-IDF DataFrame
train_copy2 = pd.concat([train_copy2, tfidf_df], axis=1)
test_copy2 = pd.concat([test_copy2, tfidf_df2], axis=1)
# Display the result
In [ ]:
hey = pd.read_csv("training.csv")
In [ ]:
hey
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
def calculate_aqi_o3(concentration):
    # AQI breakpoints for ozone (O3)
    breakpoints = [(0, 50), (51, 100), (101, 150), (151, 200), (201, 300), (301, 400), (401, 500)]
    concentrations = [0, 0.054, 0.070, 0.085, 0.105, 0.2, 0.504]  # Ozone concentration values (ppm)
    
    for i in range(len(breakpoints)):
        low, high = breakpoints[i]
        if low <= concentration <= high:
            aqi_low, aqi_high = concentrations[i], concentrations[i+1]
            aqi_low_index, aqi_high_index = breakpoints[i]
            aqi = ((aqi_high - aqi_low) / (aqi_high_index - aqi_low_index)) * (concentration - aqi_low_index) + aqi_low
            return round(aqi)
    # Return a default value if concentration is outside the range
    return 0
In [ ]:
def calculate_aqi_pm25(concentration):
    # AQI breakpoints for PM2.5
    breakpoints = [(0, 12), (12.1, 35.4), (35.5, 55.4), (55.5, 150.4), (150.5, 250.4), (250.5, 350.4), (350.5, 500.4)]
    aqi_low = [0, 51, 101, 151, 201, 301, 401]  # PM2.5 AQI values
    
    for i, (low, high) in enumerate(breakpoints):
        if low <= concentration <= high:
            aqi_low_index, aqi_high_index = aqi_low[i], aqi_low[i+1]
            aqi = ((aqi_high_index - aqi_low_index) / (high - low)) * (concentration - low) + aqi_low_index
            return round(aqi)
        
    # Return a default value if concentration is outside the range
    return 0
In [ ]:
def calculate_aqi_no2(concentration):
    # AQI breakpoints for NO2
    breakpoints = [(0, 53), (54, 100), (101, 360), (361, 649), (650, 1249), (1250, 1649), (1650, 2049)]
    aqi_low = [0, 51, 101, 151, 201, 301, 401]  # NO2 AQI values
    
    for i, (low, high) in enumerate(breakpoints):
        if low <= concentration <= high:
            aqi_low_index, aqi_high_index = aqi_low[i], aqi_low[i+1]
            aqi = ((aqi_high_index - aqi_low_index) / (high - low)) * (concentration - low) + aqi_low_index
            return round(aqi)
    
    # Return a default value if concentration is outside the range
    return 0
In [ ]:
def calculate_overall_aqi(o3_concentration, pm25_concentration, no2_concentration):
    # Calculate AQI for each pollutant
    o3_aqi = calculate_aqi_o3(o3_concentration)
    pm25_aqi = calculate_aqi_pm25(pm25_concentration)
    no2_aqi = calculate_aqi_no2(no2_concentration)
    
    # Determine the highest AQI value
    overall_aqi = max(o3_aqi, pm25_aqi, no2_aqi)
    
    return overall_aqi
In [ ]:
def add_fe2(df) : 

    aqi_index = []

    for i in range(len(df['Ozone'])):
        o3_concentration = df['Ozone'].iloc[i]
        pm25_concentration = df['PM25'].iloc[i]
        no2_concentration = df['N02'].iloc[i]

        aqi_index.append(calculate_overall_aqi(o3_concentration, pm25_concentration, no2_concentration))

    # Create a new column for AQI
    df['aqi_index'] = np.array(aqi_index)
    
    return df 
In [ ]:
# train_copy2 = add_fe2(train_copy2)
# test_copy2 = add_fe2(test_copy2)
In [ ]:
def add_fe(df) : 
    def calculate_immunity_index(age, aqi):
        # Define rules to calculate immunity index based on age and AQI
        if age < 18:
            # Children have higher immunity
            immunity = 0.8
        elif age >= 18 and age < 65:
            # Adults have moderate immunity
            immunity = 0.6
        else:
            # Elderly have lower immunity
            immunity = 0.4

        # Adjust immunity based on AQI
        if aqi > 200:
            # Very poor air quality affects immunity negatively
            immunity *= 0.5
        elif aqi > 100:
            # Poor air quality affects immunity moderately
            immunity *= 0.7
        elif aqi > 50:
            # Moderate air quality has slight effect on immunity
            immunity *= 0.9

        return immunity
    immunity_index = []

    for i in range(len(df['patient_age'])):
        
        immunity_index.append(calculate_immunity_index(df['patient_age'].iloc[i], df['aqi_index'].iloc[i]))

    # Create a new column for immunity
    df['immunity_index'] = immunity_index
    
    
    return df
In [ ]:
# train_copy2 = add_fe(train_copy2)
# test_copy2 = add_fe(test_copy2)
In [ ]:
def add_fe3(df) : 
    
    df['environmental_exposure'] = df['Ozone'] + df['PM25'] + df['N02']

    # Create a new column for socioeconomic status index
    df['socioeconomic_status'] = df['income_household_median'] * df['education_college_or_above']

    # Create a new column for health status index
    df['health_status'] = df['health_uninsured'] + df['farmer'] + df['disabled']

    # Create a new column for regional demographic characteristics
    df['regional_demographics'] = df['patient_state'] + '_' + df['patient_zip3'].astype(str)

    # Create a new column for the interaction term
    df['age_income_interaction'] = df['patient_age'] * df['income_household_median']
    
    weight_age = 0.45  # Age might have a moderate impact on immunity
    weight_aqi = 0.4  # Air quality index could significantly affect immunity
    weight_socioeconomic_status = 0.01  # Socioeconomic status could impact immunity
    weight_environmental_exposure = 0.25  # Environmental exposure might affect immunity
    weight_health_status = 0.01  # Overall health status could influence immunity
    weight_age_adjusted_bmi = 0.35  # Age-adjusted BMI could contribute to immunity

    # Calculate an initial value for the immunity index based on the provided features
    df['immunity_index'] = (
        df['patient_age'] * weight_age +
        df['aqi_index'] * weight_aqi +
        df['socioeconomic_status'] * weight_socioeconomic_status +
        df['environmental_exposure'] * weight_environmental_exposure +
        df['health_status'] * weight_health_status +
        df['ratio'] * weight_age_adjusted_bmi + 
        df['immunity_index'] * weight_age_adjusted_bmi
    )
    return df
In [ ]:
# train_copy2 = add_fe3(train_copy2)
# test_copy2 = add_fe3(test_copy2)
In [ ]:
def add_fe4(df) : 

    df['chemical_interaction'] = df.apply(lambda row: 'Yes' if row['farmer'] > 20 or row['veteran'] > 20 else 'No', axis=1)
#     def categorize_bmi(bmi_value):
#         if bmi_value < 18.5:
#             return 'Underweight'
#         elif 18.5 <= bmi_value < 25:
#             return 'Normal Weight'
#         elif 25 <= bmi_value < 30:
#             return 'Overweight'
#         else:
#             return 'Obese'
        
#     df['bmi_category'] = df['bmi'].apply(categorize_bmi)

#     def find_dominant_age_group(row):
#         age_cols = ['age_under_10', 'age_10_to_19', 'age_20s', 'age_30s', 'age_40s', 'age_50s', 'age_60s', 'age_70s', 'age_over_80']
#         max_age_col = max(age_cols, key=lambda col: row[col] if isinstance(row[col], (int, float)) else float('-inf'))
#         return max_age_col

#     # Define a function to categorize age groups
#     def categorize_age_group(age_group):
#         if pd.isnull(age_group):
#             return 'Unknown'
#         if age_group.startswith('age_under_10'):
#             return 'Childhood/Adolescence'
#         elif age_group.startswith('age_10_to_19'):
#             return 'Childhood/Adolescence'
#         elif age_group.startswith('age_20'):
#             return 'Young Adulthood'
#         elif age_group.startswith('age_30'):
#             return 'Young Adulthood'
#         elif age_group.startswith('age_40'):
#             return 'Middle Adulthood'
#         elif age_group.startswith('age_50'):
#             return 'Middle Adulthood'
#         elif age_group.startswith('age_60'):
#             return 'Older Adulthood'
#         elif age_group.startswith('age_70'):
#             return 'Older Adulthood'
#         elif age_group.startswith('age_over_80'):
#             return 'Older Adulthood'

#     # Define a function to categorize family type
#     def categorize_family_type(row):
#         dominant_age_group = find_dominant_age_group(row)
#         age_category = categorize_age_group(dominant_age_group)
#         if age_category == 'Childhood/Adolescence':
#             if row['patient_age'] < 18:
#                 return 'Child Household with Child Patient'
#             else:
#                 return 'Child Household with Adolescent Patient'
#         elif age_category == 'Young Adulthood':
#             if row['patient_age'] < 35:
#                 return 'Young Adult Household with Young Adult Patient'
#             else:
#                 return 'Young Adult Household with Middle Adult Patient'
#         elif age_category == 'Middle Adulthood':
#             if row['patient_age'] < 60:
#                 return 'Middle Adult Household with Middle Adult Patient'
#             else:
#                 return 'Middle Adult Household with Older Adult Patient'
#         else:
#             return 'Old Adult Household with Older Adult Patient'

#     # Apply the function to derive family type for X_train
#     df['family_type'] = df.apply(categorize_family_type, axis=1)

    
    
    return df 

train_copy2 = add_fe4(train_copy2)
test_copy2 = add_fe4(test_copy2)
In [ ]:
train_copy2.chemical_interaction.value_counts()
In [ ]:
train_copy2['fast_new'] = train_copy2['chemical_interaction'].astype(str)+'_'+train_copy2['ICD10'].astype(str)+train_copy2['new_feature15']+train_copy2['AgeCat'].astype(str)
In [ ]:
test_copy2['fast_new'] = test_copy2['chemical_interaction'].astype(str)+'_'+test_copy2['ICD10'].astype(str)+train_copy2['new_feature15']
In [ ]:
train_copy2['fast_new'].nunique()
In [ ]:
sns.countplot(x='fast_new', hue='DiagPeriodL90D', data=train_copy2)
plt.title('Countplot of new_feature by DiagPeriodL90D')
# plt.savefig('countplot.png')  # Save the plot as a PNG file

plt.show()
In [ ]:
contingency_table = pd.crosstab(train_copy2['fast_new'], train_copy['DiagPeriodL90D'])
contingency_table
In [ ]:
 
In [ ]:
train_copy2 = drop_column(train_copy2 , "breast_cancer_diagnosis_desc")
test_copy2 = drop_column(test_copy2 , "breast_cancer_diagnosis_desc")
In [ ]:
# train_copy2.drop(dropped , axis=1 , inplace =True)
# test_copy2.drop(dropped , axis=1 , inplace =True)
In [ ]:
oof = train_copy2[['DiagPeriodL90D']]
folds = Stock.folds
preds1=[]
log = []
X= train_copy2.drop('DiagPeriodL90D' , axis=1)
TEST= test_copy2


misclassified_indices_per_fold = []

y = train_copy2.DiagPeriodL90D

for j,targ in enumerate(['DiagPeriodL90D']) : 
#     y = train[targ]
    print(50*'--')
    print(f'Training k-Fold Model for Target {targ}')
    print(50*'--')
    for i,( train_index, test_index) in enumerate(folds.split(X, y)):

        print(50*'--')
        print(f'Fold {i+1}/{5}')
        print(50*'--')
        
        X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]
#   class_weights = {0: 0.7 , 1 : 0.3} ,          
      # Train model
#         stock_index.append(X_test.index)

        cat = CatBoostClassifier(random_seed=42 ,early_stopping_rounds=200, cat_features = [i for i in train_copy2.columns if train_copy2[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,  
                           
                                 logging_level='Silent') 
    
    
        cat.fit(X_train,y_train,eval_set=[(X_train,y_train),(X_test, y_test)], plot= True)
        
        
       


#         # Create a SHAP explainer object
#         explainer = shap.TreeExplainer(cat)
#         # Calculate SHAP values for the test set
#         shap_values = explainer.shap_values(X_test )

#         # Summary Plot to visualize feature importance
#         shap.summary_plot(shap_values, X_test, feature_names=X.columns, plot_type='bar',max_display=len(X.columns))

        # Alternatively, you can plot a summary plot for a specific instance
        # For example, for the first instance in the test set
        
        
        
        calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        calibrated_classifier.fit(X_train,y_train)
        
#         calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        # Fold Evaluation
        
#         calibrated_classifier.fit(X_train, y_train)
#         fold_pred   = model.predict_proba(X_test)
        print(50*'**')
        y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
        y_pred = calibrated_classifier.predict(X_test )
#         y_pred = [1 if i >0.78 else 0 for i in y_pred_prob ]
        print(y_pred_prob , calibrated_classifier.predict_proba(X_test)[:, 1])
        accuracy = accuracy_score(y_test, y_pred)
        
#         y_pred = [1 if i >0.55 else 0 for i in y_pred_prob ]
        roc_auc = roc_auc_score(y_test, y_pred_prob)
        conf_matrix = confusion_matrix(y_test, y_pred)
        loss = roc_auc

        print(f'Accuracy: {accuracy:.4f}')
        print(f'ROC AUC: {roc_auc:.4f}')

        print('\nClassification Report:')
        print(classification_report(y_test, y_pred))
        print(f"log_loss validation Fold {i+1}/{5} is   : {loss}" )
        log.append(loss)    
        print(50*'**')
        #update oof
        

        # Test Evaluation
        
        test_proba = calibrated_classifier.predict_proba(TEST)

        preds1.append(test_proba)
        
        
        



            
            
        conf_mat  = confusion_matrix(y_test, y_pred) 
        plt.figure(figsize=(8, 6))
        sns.set(font_scale=1.2)
        sns.set_style("whitegrid", {"axes.edgecolor": ".6", "grid.color": ".6"})

        cmap = sns.color_palette("viridis", as_cmap=True)
        heatmap = sns.heatmap(conf_matrix, annot=True, fmt='d', cmap=cmap, annot_kws={'size': 14}, cbar=False)

        heatmap.set_title('Confusion Matrix', fontdict={'fontsize': 16})
        heatmap.set_xlabel('Predicted', fontdict={'fontsize': 14})
        heatmap.set_ylabel('True', fontdict={'fontsize': 14})
        
        
        
        fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
        roc_auc = auc(fpr, tpr)

        fig = go.Figure()
        fig.add_trace(go.Scatter(x=fpr, y=tpr, mode='lines', 
                                 line=dict(color='#FF4505', width=5),
                                 name=f'AUC = {roc_auc:.2f}'))

        fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', 
                                 line=dict(color='navy', width=2, dash='dash'),
                                 name='Random'))

        fig.update_layout(
            title='ROC Curve',
            xaxis=dict(title='False Positive Rate'),
            yaxis=dict(title='True Positive Rate'),
            legend=dict(x=0.02, y=0.98),
            width=800, height=800
        )

        fig.show()
        
        threshold = 0.5
        y_pred_binary = (y_pred_prob > threshold).astype(int)
        misclassified_indices = np.where(y_pred_binary != y_test)[0]
        misclassified_indices_per_fold.append(misclassified_indices)
        

plt.show()
print(50*'##')
print(f"The overall loss is {np.array(log).mean()}")



all_misclassified_indices = np.concatenate(misclassified_indices_per_fold)

print("Indices of misclassified instances:")
print(all_misclassified_indices) 
In [ ]:
 
In [ ]:
score(train_copy2 , test_copy2)
In [ ]:
dropped
In [ ]:
train_copy3 = drop_column(train_copy2, 'of')
test_copy3 = drop_column(test_copy2, 'of')
# score1 = score(train_copy3, test_copy3)
In [ ]:
train_copy3 = drop_column(train_copy3, 'inner')
test_copy3 = drop_column(test_copy3, 'inner')
In [ ]:
oof = train_copy3[['DiagPeriodL90D']]
folds = Stock.folds
preds1=[]
log = []
X= train_copy3.drop('DiagPeriodL90D' , axis=1)
TEST= test_copy3


misclassified_indices_per_fold = []

y = train_copy3.DiagPeriodL90D

for j,targ in enumerate(['DiagPeriodL90D']) : 
#     y = train[targ]
    print(50*'--')
    print(f'Training k-Fold Model for Target {targ}')
    print(50*'--')
    for i,( train_index, test_index) in enumerate(folds.split(X, y)):

        print(50*'--')
        print(f'Fold {i+1}/{5}')
        print(50*'--')
        
        X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]
#   class_weights = {0: 0.7 , 1 : 0.3} ,          
      # Train model
#         stock_index.append(X_test.index)

        cat = CatBoostClassifier(random_seed=42 ,early_stopping_rounds=200, cat_features = [i for i in train_copy2.columns if train_copy2[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,  
                           
                                 logging_level='Silent',) 
    
    
        cat.fit(X_train,y_train,eval_set=[(X_train,y_train),(X_test, y_test)], plot= True)
        
        
       


#         # Create a SHAP explainer object
#         explainer = shap.TreeExplainer(cat)
#         # Calculate SHAP values for the test set
#         shap_values = explainer.shap_values(X_test )

#         # Summary Plot to visualize feature importance
#         shap.summary_plot(shap_values, X_test, feature_names=X.columns, plot_type='bar',max_display=len(X.columns))

        # Alternatively, you can plot a summary plot for a specific instance
        # For example, for the first instance in the test set
        
        
        
        calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        calibrated_classifier.fit(X_train,y_train)
        
#         calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        # Fold Evaluation
        
#         calibrated_classifier.fit(X_train, y_train)
#         fold_pred   = model.predict_proba(X_test)
        print(50*'**')
        y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
        y_pred = calibrated_classifier.predict(X_test )
#         y_pred = [1 if i >0.78 else 0 for i in y_pred_prob ]
        print(y_pred_prob , calibrated_classifier.predict_proba(X_test)[:, 1])
        accuracy = accuracy_score(y_test, y_pred)
        
#         y_pred = [1 if i >0.55 else 0 for i in y_pred_prob ]
        roc_auc = roc_auc_score(y_test, y_pred_prob)
        conf_matrix = confusion_matrix(y_test, y_pred)
        loss = roc_auc

        print(f'Accuracy: {accuracy:.4f}')
        print(f'ROC AUC: {roc_auc:.4f}')

        print('\nClassification Report:')
        print(classification_report(y_test, y_pred))
        print(f"log_loss validation Fold {i+1}/{5} is   : {loss}" )
        log.append(loss)    
        print(50*'**')
        #update oof
        

        # Test Evaluation
        
        test_proba = calibrated_classifier.predict_proba(TEST)

        preds1.append(test_proba)
        
        
        



            
            
        conf_mat  = confusion_matrix(y_test, y_pred) 
        plt.figure(figsize=(8, 6))
        sns.set(font_scale=1.2)
        sns.set_style("whitegrid", {"axes.edgecolor": ".6", "grid.color": ".6"})

        cmap = sns.color_palette("viridis", as_cmap=True)
        heatmap = sns.heatmap(conf_matrix, annot=True, fmt='d', cmap=cmap, annot_kws={'size': 14}, cbar=False)

        heatmap.set_title('Confusion Matrix', fontdict={'fontsize': 16})
        heatmap.set_xlabel('Predicted', fontdict={'fontsize': 14})
        heatmap.set_ylabel('True', fontdict={'fontsize': 14})
        
        
        
        fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
        roc_auc = auc(fpr, tpr)

        fig = go.Figure()
        fig.add_trace(go.Scatter(x=fpr, y=tpr, mode='lines', 
                                 line=dict(color='#FF4505', width=5),
                                 name=f'AUC = {roc_auc:.2f}'))

        fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', 
                                 line=dict(color='navy', width=2, dash='dash'),
                                 name='Random'))

        fig.update_layout(
            title='ROC Curve',
            xaxis=dict(title='False Positive Rate'),
            yaxis=dict(title='True Positive Rate'),
            legend=dict(x=0.02, y=0.98),
            width=800, height=800
        )

        fig.show()
        
        threshold = 0.5
        y_pred_binary = (y_pred_prob > threshold).astype(int)
        misclassified_indices = np.where(y_pred_binary != y_test)[0]
        misclassified_indices_per_fold.append(misclassified_indices)
        

plt.show()
print(50*'##')
print(f"The overall loss is {np.array(log).mean()}")



all_misclassified_indices = np.concatenate(misclassified_indices_per_fold)

print("Indices of misclassified instances:")
print(all_misclassified_indices) 
In [ ]:
score(train_copy3, test_copy3)
In [ ]:
from tqdm import tqdm

max_score = 0.8099246010824646
dropped = []
selected_features = list(set(test_copy2.columns) - set(test_copy.columns))

for col in tqdm(selected_features, desc="Adding Features Progress") : 
    print(f"working on {col} ......")
    train_copy3 = train_copy2.copy(deep =True)
    test_copy3 = test_copy2.copy(deep =True)
    train_copy3 = drop_column(train_copy2, col)
    test_copy3 = drop_column(test_copy2, col)
    score1 = score(train_copy3, test_copy3)
    if score1>max_score : 
        
        dropped.append(col)
        
        max_score = score1
        print(f"imporved score to {max_score}")
        
        if max_score>0.81:
            break
        train_copy2 = train_copy3.copy(deep = True)
        test_copy2 = test_copy3.copy(deep = True)
        
    else : 
        continue
In [ ]:
score(train_copy3, test_copy3)
In [ ]:
test_copy3.drop('malignant',axis=1 , inplace =True)
In [ ]:
from tqdm import tqdm

max_score = 0.8099246010824646
dropped = []
selected_features = list(reversed(list(set(test_copy2.columns) - set(test_copy.columns))))

for col in tqdm(selected_features, desc="Adding Features Progress") : 
    print(f"working on {col} ......")
    train_copy3 = train_copy2.copy(deep =True)
    test_copy3 = test_copy2.copy(deep =True)
    train_copy3 = drop_column(train_copy3, col)
    test_copy3 = drop_column(test_copy3, col)
    score1 = score(train_copy3, test_copy3)
    if score1>max_score : 
        dropped.append(col)
        max_score = score1
        print(f"imporved score to {max_score}")
        train_copy2 = train_copy3.copy(deep = True)
        test_copy2 = test_copy3.copy(deep = True)
        
    else : 
        continue
In [ ]:
train_copy2
In [ ]:
# train_copy2.to_csv('last_train2.csv' , index = False)
# test_copy2.to_csv('last_test2.csv' , index = False)
In [ ]:
X= train_copy.drop('DiagPeriodL90D' , axis=1)
y = train_copy.DiagPeriodL90D
X_train , X_test , y_train , y_test  = train_test_split(X, y ,test_size= 0.2)
def objective(trial):
    # Define hyperparameters to be optimized
    cat_params = {
        'iterations': trial.suggest_int('iterations', 50, 1000),
        'learning_rate': trial.suggest_float('learning_rate', 0.001, 0.1),
        'depth': trial.suggest_int('depth', 4, 10),
#         'class_weights': {0: trial.suggest_float('class_weight_0', 0.1, 0.9), 1: 1.0},
      
 
        # Add other hyperparameters you want to optimize
    }

    # Initialize lists to store results for each fold
    auc_scores = []

    for i, (train_index, test_index) in enumerate(folds.split(X, y)):
        X_fold_train, X_fold_test = X.iloc[train_index], X.iloc[test_index]
        y_fold_train, y_fold_test = y.iloc[train_index], y.iloc[test_index]

        # Train model
        cat = CatBoostClassifier(**cat_params, random_seed=42 ,early_stopping_rounds=100, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,
                      
                                 logging_level='Silent'   ) 
        cat.fit(X_fold_train, y_fold_train, eval_set=[(X_fold_train, y_fold_train), (X_fold_test, y_fold_test)])

        # Evaluate model on the fold
        y_pred_prob = cat.predict_proba(X_fold_test)[:, 1]
        auc = roc_auc_score(y_fold_test, y_pred_prob)
        auc_scores.append(auc)

    # Compute mean AUC across folds
    mean_auc = np.mean(auc_scores)

    # Return the negative mean AUC since Optuna aims to minimize the objective
    return mean_auc

# Create an Optuna study and run the optimization
study = optuna.create_study(direction='maximize')
study.optimize(objective, n_trials=100 , show_progress_bar= True  )  # You can adjust the number of trials

# Get the best hyperparameters
best_params = study.best_params
In [ ]:
selected_features
In [ ]:
dropped
In [ ]:
max_score
In [ ]:
train_copy2
In [ ]:
plot_features = pd.DataFrame()
plot_features['features'] = cat.feature_names_
plot_features['features_importance'] = cat.feature_importances_
n_top_feats = 60
plt.figure(figsize=(16, 16))
sns.barplot(data=plot_features.sort_values(by='features_importance', ascending=False).head(n_top_feats), x='features_importance', y='features');
plt.title(f'{n_top_feats} TOP feature importance');
In [ ]:
 
In [ ]:
first three features give The overall loss is 0.8069714397624427 what corresponds to 0.808 in the LB without any HPT
In [ ]:
The overall loss is 0.8054414614500329
In [ ]:
0.8063573003363146
In [ ]:
0.8051022578238735
In [ ]:
0.8046878276595008
In [ ]:
plot_features
In [ ]:
plot_features[plot_features['features'] == 'ICD10']
In [ ]:
plot_features = pd.DataFrame()
plot_features['features'] = cat.feature_names_
plot_features['features_importance'] = cat.feature_importances_
n_top_feats = 60
plt.figure(figsize=(16, 16))
sns.barplot(data=plot_features.sort_values(by='features_importance', ascending=False).head(n_top_feats), x='features_importance', y='features');
plt.title(f'{n_top_feats} TOP feature importance');
In [ ]:
#early_stopping_rounds=200 means leave if no improvement in 200 successif iteration
best_iteration = cat.get_best_iteration()
print("Best Iteration:", best_iteration)



#benefit :
#Use the Best Iteration for Prediction: : #predictions = model.predict(X_test, ntree_end=best_iteration)
#Retrieve the Best Model: # Create a new model using the best iteration 
#best_model = CatBoostClassifier(iterations=best_iteration and same other parameters as before
In [ ]:
cat.best_score_
In [ ]:
cat.drop_unused_features
In [ ]:
cat.get_all_params()
In [ ]:
update_train = train_copy[cat.feature_names_]
update_test = test_copy[cat.feature_names_]

update_train['DiagPeriodL90D'] = Stock.y
In [ ]:
 
In [ ]:
class Stock : 
    n,_ = train.shape
    y = train.DiagPeriodL90D
    n_splits =5
    folds = StratifiedKFold(n_splits = n_splits)
In [ ]:
oof = update_train[['DiagPeriodL90D']]
folds = Stock.folds
preds1=[]
log = []
X= update_train.drop('DiagPeriodL90D' , axis=1)
TEST= update_test
stock_index= []

misclassified_indices_per_fold = []

y = update_train.DiagPeriodL90D

for j,targ in enumerate(['DiagPeriodL90D']) : 
#     y = train[targ]
    print(50*'--')
    print(f'Training k-Fold Model for Target {targ}')
    print(50*'--')
    for i,( train_index, test_index) in enumerate(folds.split(X, y)):

        print(50*'--')
        print(f'Fold {i+1}/{5}')
        print(50*'--')
        
        X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]
#   class_weights = {0: 0.7 , 1 : 0.3} ,          
      # Train model
#         stock_index.append(X_test.index)
        cat = CatBoostClassifier(random_seed=42 ,early_stopping_rounds=100, cat_features = [i for i in update_train.columns if train[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,
                                 class_weights = {0: 0.7 , 1 : 0.3} ,
                                 logging_level='Silent'   )
                             
                              
                                 
                                 
                                 
                                 
                                 
                                 
        cat.fit(X_train,y_train,eval_set=[(X_train,y_train),(X_test, y_test)] ,  plot=True)
        calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        calibrated_classifier.fit(X_train,y_train)
        
#         calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        # Fold Evaluation
        
#         calibrated_classifier.fit(X_train, y_train)
#         fold_pred   = model.predict_proba(X_test)
        print(50*'**')
        y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
        y_pred = calibrated_classifier.predict(X_test )
#         y_pred = [1 if i >0.78 else 0 for i in y_pred_prob ]
        print(y_pred_prob , calibrated_classifier.predict_proba(X_test)[:, 1])
        accuracy = accuracy_score(y_test, y_pred)
        
#         y_pred = [1 if i >0.55 else 0 for i in y_pred_prob ]
        roc_auc = roc_auc_score(y_test, y_pred_prob)
        conf_matrix = confusion_matrix(y_test, y_pred)
        loss = roc_auc

        print(f'Accuracy: {accuracy:.4f}')
        print(f'ROC AUC: {roc_auc:.4f}')

        print('\nClassification Report:')
        print(classification_report(y_test, y_pred))
        print(f"log_loss validation Fold {i+1}/{5} is   : {loss}" )
        log.append(loss)    
        print(50*'**')
        #update oof
        

        # Test Evaluation
        
        test_proba = calibrated_classifier.predict_proba(TEST)

        preds1.append(test_proba)
        
        
        



            
            
        conf_mat  = confusion_matrix(y_test, y_pred) 
        plt.figure(figsize=(8, 6))
        sns.set(font_scale=1.2)
        sns.set_style("whitegrid", {"axes.edgecolor": ".6", "grid.color": ".6"})

        cmap = sns.color_palette("viridis", as_cmap=True)
        heatmap = sns.heatmap(conf_matrix, annot=True, fmt='d', cmap=cmap, annot_kws={'size': 14}, cbar=False)

        heatmap.set_title('Confusion Matrix', fontdict={'fontsize': 16})
        heatmap.set_xlabel('Predicted', fontdict={'fontsize': 14})
        heatmap.set_ylabel('True', fontdict={'fontsize': 14})
        
        
        
        fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
        roc_auc = auc(fpr, tpr)

        fig = go.Figure()
        fig.add_trace(go.Scatter(x=fpr, y=tpr, mode='lines', 
                                 line=dict(color='#FF4505', width=5),
                                 name=f'AUC = {roc_auc:.2f}'))

        fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', 
                                 line=dict(color='navy', width=2, dash='dash'),
                                 name='Random'))

        fig.update_layout(
            title='ROC Curve',
            xaxis=dict(title='False Positive Rate'),
            yaxis=dict(title='True Positive Rate'),
            legend=dict(x=0.02, y=0.98),
            width=800, height=800
        )

        fig.show()
        
        threshold = 0.5
        y_pred_binary = (y_pred_prob > threshold).astype(int)
        misclassified_indices = np.where(y_pred_binary != y_test)[0]
        misclassified_indices_per_fold.append(misclassified_indices)
        stock_index.append(X_test.index)

plt.show()
print(50*'##')
print(f"The overall loss is {np.array(log).mean()}")



all_misclassified_indices = np.concatenate(misclassified_indices_per_fold)

print("Indices of misclassified instances:")
print(all_misclassified_indices) 
In [ ]:
cat.get_scale_and_bias()
In [ ]:
The overall loss is 0.8063898595150565
In [ ]:
best_iteration = cat.get_best_iteration()
print("Best Iteration:", best_iteration ) #fixe
In [ ]:
plot_features = pd.DataFrame()
plot_features['features'] = cat.feature_names_
plot_features['features_importance'] = cat.feature_importances_
n_top_feats = 40
plt.figure(figsize=(16, 16))
sns.barplot(data=plot_features.sort_values(by='features_importance', ascending=False).head(n_top_feats), x='features_importance', y='features');
plt.title(f'{n_top_feats} TOP feature importance');
In [ ]:
cat.get_n_features_in()
In [ ]:
train.DiagPeriodL90D.value_counts()
In [ ]:
# analyse = update_train.iloc[X_test.index]
# analyse_2 = analyse[analyse['DiagPeriodL90D'] ==1]
In [ ]:
# train_copy2= update_train.drop(analyse.index)
In [ ]:
# class Stock : 
#     n,_ = train.shape
#     y = train.DiagPeriodL90D
#     n_splits =5
#     folds = StratifiedKFold(n_splits = n_splits)
In [ ]:
# oof = train_copy2[['DiagPeriodL90D']]
# folds = Stock.folds
# preds1=[]
# log = []
# X= train_copy2.drop('DiagPeriodL90D' , axis=1)
# TEST= update_test
# stock_index= []

# misclassified_indices_per_fold = []

# y = train_copy2.DiagPeriodL90D

# for j,targ in enumerate(['DiagPeriodL90D']) : 
# #     y = train[targ]
#     print(50*'--')
#     print(f'Training k-Fold Model for Target {targ}')
#     print(50*'--')
#     for i,( train_index, test_index) in enumerate(folds.split(X, y)):

#         print(50*'--')
#         print(f'Fold {i+1}/{5}')
#         print(50*'--')
        
#         X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]
# #   class_weights = {0: 0.7 , 1 : 0.3} ,          
#       # Train model
# #         stock_index.append(X_test.index)
#         cat = CatBoostClassifier(random_seed=42 ,early_stopping_rounds=100, cat_features = [i for i in update_train.columns if train[i].dtype == 'object'], 
#                                  loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
#                                 text_features = ['breast_cancer_diagnosis_desc'] ,
#                                  class_weights = {0: 0.7 , 1 : 0.3} ,
#                                  logging_level='Silent'   )
                             
                              
                                 
                                 
                                 
                                 
                                 
                                 
#         cat.fit(X_train,y_train,eval_set=[(X_train,y_train),(X_test, y_test)] ,  plot=True)
#         calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
#         calibrated_classifier.fit(X_train,y_train)
        
# #         calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
#         # Fold Evaluation
        
# #         calibrated_classifier.fit(X_train, y_train)
# #         fold_pred   = model.predict_proba(X_test)
#         print(50*'**')
#         y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
#         y_pred = calibrated_classifier.predict(X_test )
# #         y_pred = [1 if i >0.78 else 0 for i in y_pred_prob ]
#         print(y_pred_prob , calibrated_classifier.predict_proba(X_test)[:, 1])
#         accuracy = accuracy_score(y_test, y_pred)
        
# #         y_pred = [1 if i >0.55 else 0 for i in y_pred_prob ]
#         roc_auc = roc_auc_score(y_test, y_pred_prob)
#         conf_matrix = confusion_matrix(y_test, y_pred)
#         loss = roc_auc

#         print(f'Accuracy: {accuracy:.4f}')
#         print(f'ROC AUC: {roc_auc:.4f}')

#         print('\nClassification Report:')
#         print(classification_report(y_test, y_pred))
#         print(f"log_loss validation Fold {i+1}/{5} is   : {loss}" )
#         log.append(loss)    
#         print(50*'**')
#         #update oof
        

#         # Test Evaluation
        
#         test_proba = calibrated_classifier.predict_proba(TEST)

#         preds1.append(test_proba)
        
        
        



            
            
#         conf_mat  = confusion_matrix(y_test, y_pred) 
#         plt.figure(figsize=(8, 6))
#         sns.set(font_scale=1.2)
#         sns.set_style("whitegrid", {"axes.edgecolor": ".6", "grid.color": ".6"})

#         cmap = sns.color_palette("viridis", as_cmap=True)
#         heatmap = sns.heatmap(conf_matrix, annot=True, fmt='d', cmap=cmap, annot_kws={'size': 14}, cbar=False)

#         heatmap.set_title('Confusion Matrix', fontdict={'fontsize': 16})
#         heatmap.set_xlabel('Predicted', fontdict={'fontsize': 14})
#         heatmap.set_ylabel('True', fontdict={'fontsize': 14})
        
        
        
#         fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
#         roc_auc = auc(fpr, tpr)

#         fig = go.Figure()
#         fig.add_trace(go.Scatter(x=fpr, y=tpr, mode='lines', 
#                                  line=dict(color='#FF4505', width=5),
#                                  name=f'AUC = {roc_auc:.2f}'))

#         fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', 
#                                  line=dict(color='navy', width=2, dash='dash'),
#                                  name='Random'))

#         fig.update_layout(
#             title='ROC Curve',
#             xaxis=dict(title='False Positive Rate'),
#             yaxis=dict(title='True Positive Rate'),
#             legend=dict(x=0.02, y=0.98),
#             width=800, height=800
#         )

#         fig.show()
        
#         threshold = 0.5
#         y_pred_binary = (y_pred_prob > threshold).astype(int)
#         misclassified_indices = np.where(y_pred_binary != y_test)[0]
#         misclassified_indices_per_fold.append(misclassified_indices)
#         stock_index.append(X_test.index)

# plt.show()
# print(50*'##')
# print(f"The overall loss is {np.array(log).mean()}")



# all_misclassified_indices = np.concatenate(misclassified_indices_per_fold)

# print("Indices of misclassified instances:")
# print(all_misclassified_indices) 
In [ ]:
hereee
In [ ]:
{'iterations': 972,
 'learning_rate': 0.09715326114858114,
 'depth': 4,
 'subsample': 0.9719096521763939}
In [ ]:
best_params
In [ ]:
# Assuming your target variable is binary and named 'DiagPeriodL90D'
y = train_copy['DiagPeriodL90D']

# Set the number of splits
n_splits = 5

# Initialize StratifiedKFold without shuffle
stratified_kfold = StratifiedKFold(n_splits=n_splits)

# Get the indices for each fold
fold_indices = list(stratified_kfold.split(X, y))

# Define the second fold indices
second_fold_train_index, second_fold_test_index = fold_indices[1]

# Define a function to train the model using specific hyperparameters and indices
def train_model_with_params(X_train, y_train, X_test, y_test, cat_params):
    cat = CatBoostClassifier(**cat_params, random_seed=42, early_stopping_rounds=200, 
                             cat_features=[i for i in train_copy.columns if train_copy[i].dtype == 'object'] + ["patient_zip3"],
                             loss_function="Logloss", use_best_model=True, eval_metric="AUC", 
                             text_features=['breast_cancer_diagnosis_desc'], logging_level='Silent')

    cat.fit(X_train, y_train, eval_set=[(X_train, y_train), (X_test, y_test)])
    y_pred_prob = cat.predict_proba(X_test)[:, 1]
    auc = roc_auc_score(y_test, y_pred_prob)
    
    return auc

def objective(trial):
    # Define hyperparameters to be optimized
    cat_params = {
        'iterations': trial.suggest_int('iterations', 50, 1000),
        'learning_rate': trial.suggest_float('learning_rate', 0.001, 0.1),
        'depth': trial.suggest_int('depth', 4, 10),
        'subsample': trial.suggest_float('subsample', 0.5, 1.0),
        # Add other hyperparameters you want to optimize
    }

    # Extract second fold data
    X_second_fold_train, X_second_fold_test = X.iloc[second_fold_train_index], X.iloc[second_fold_test_index]
    y_second_fold_train, y_second_fold_test = y.iloc[second_fold_train_index], y.iloc[second_fold_test_index]

    # Train model on the second fold
    auc_second_fold = train_model_with_params(X_second_fold_train, y_second_fold_train, X_second_fold_test, y_second_fold_test, cat_params)

    return auc_second_fold

# Create an Optuna study and run the optimization
study = optuna.create_study(direction='maximize')
study.optimize(objective, n_trials=100, show_progress_bar=True)

# Get the best hyperparameters
best_params = study.best_params
print("Best Hyperparameters:", best_params)

for i, (train_index, test_index) in enumerate(fold_indices):
    if i == 1:
        continue  # Skip the second fold
    X_fold_train, X_fold_test = X.iloc[train_index], X.iloc[test_index]
    y_fold_train, y_fold_test = y.iloc[train_index], y.iloc[test_index]

    # Train model on other folds
    train_model_with_params(X_fold_train, y_fold_train, X_fold_test, y_fold_test, best_params)
In [ ]:
X= train_copy.drop('DiagPeriodL90D' , axis=1)
y = train_copy.DiagPeriodL90D
X_train , X_test , y_train , y_test  = train_test_split(X, y ,test_size= 0.2)
def objective(trial):
    # Define hyperparameters to be optimized
    cat_params = {
        'iterations': trial.suggest_int('iterations', 50, 1000),
        'learning_rate': trial.suggest_float('learning_rate', 0.001, 0.1),
        'depth': trial.suggest_int('depth', 4, 10),
#         'class_weights': {0: trial.suggest_float('class_weight_0', 0.1, 0.9), 1: 1.0},
      
         'l2_leaf_reg': trial.suggest_float('l2_leaf_reg', 1e-9, 10.0),
        # Add other hyperparameters you want to optimize
    }

    # Initialize lists to store results for each fold
    auc_scores = []

    for i, (train_index, test_index) in enumerate(folds.split(X, y)):
        X_fold_train, X_fold_test = X.iloc[train_index], X.iloc[test_index]
        y_fold_train, y_fold_test = y.iloc[train_index], y.iloc[test_index]

        # Train model
        cat = CatBoostClassifier(**cat_params, random_seed=42 ,early_stopping_rounds=100, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,
                      
                                 logging_level='Silent'   ) 
        cat.fit(X_fold_train, y_fold_train, eval_set=[(X_fold_train, y_fold_train), (X_fold_test, y_fold_test)])

        # Evaluate model on the fold
        y_pred_prob = cat.predict_proba(X_fold_test)[:, 1]
        auc = roc_auc_score(y_fold_test, y_pred_prob)
        auc_scores.append(auc)

    # Compute mean AUC across folds
    mean_auc = np.mean(auc_scores)

    # Return the negative mean AUC since Optuna aims to minimize the objective
    return mean_auc

# Create an Optuna study and run the optimization
study = optuna.create_study(direction='maximize')
study.optimize(objective, n_trials=100 , show_progress_bar= True  )  # You can adjust the number of trials

# Get the best hyperparameters
best_params = study.best_params
In [ ]:
{'iterations': 761,
 'learning_rate': 0.06633394185843565,
 'depth': 7,
 'l2_leaf_reg': 4.513845288655649}
In [ ]:
best_params
In [ ]:
X= train_ext.drop('DiagPeriodL90D' , axis=1)
y = train_ext.DiagPeriodL90D
X_train , X_test , y_train , y_test  = train_test_split(X, y ,test_size= 0.2)
def objective(trial):
    # Define hyperparameters to be optimized
    cat_params = {
        'iterations': trial.suggest_int('iterations', 50, 1000),
        'learning_rate': trial.suggest_float('learning_rate', 0.001, 0.1),
        'depth': trial.suggest_int('depth', 4, 10),
#         'class_weights': {0: trial.suggest_float('class_weight_0', 0.1, 0.9), 1: 1.0},
      
         'l2_leaf_reg': trial.suggest_float('l2_leaf_reg', 1e-9, 10.0),
        # Add other hyperparameters you want to optimize
    }

    # Initialize lists to store results for each fold
    auc_scores = []

    for i, (train_index, test_index) in enumerate(folds.split(X, y)):
        X_fold_train, X_fold_test = X.iloc[train_index], X.iloc[test_index]
        y_fold_train, y_fold_test = y.iloc[train_index], y.iloc[test_index]

        # Train model
        cat = CatBoostClassifier(**cat_params, random_seed=42 ,early_stopping_rounds=100, cat_features = [i for i in train_ext.columns if train_ext[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,
                      
                                 logging_level='Silent'   ) 
        cat.fit(X_fold_train, y_fold_train, eval_set=[(X_fold_train, y_fold_train), (X_fold_test, y_fold_test)])

        # Evaluate model on the fold
        y_pred_prob = cat.predict_proba(X_fold_test)[:, 1]
        auc = roc_auc_score(y_fold_test, y_pred_prob)
        auc_scores.append(auc)

    # Compute mean AUC across folds
    mean_auc = np.mean(auc_scores)

    # Return the negative mean AUC since Optuna aims to minimize the objective
    return mean_auc

# Create an Optuna study and run the optimization
study = optuna.create_study(direction='maximize')
study.optimize(objective, n_trials=100 , show_progress_bar= True  )  # You can adjust the number of trials

# Get the best hyperparameters
best_params = study.best_params
In [ ]:
# {'iterations': 791, 'learning_rate': 0.08511138894354459, 'depth': 9} with weights
In [ ]:
# cat_params = {'iterations': 658, 'learning_rate': 0.08192452733198452, 'depth': 5}
In [ ]:
X= train_copy.drop('DiagPeriodL90D' , axis=1)
y = train_copy.DiagPeriodL90D
In [ ]:
from openfe import OpenFE, tree_to_formula, transform
In [ ]:
class Stock : 
    n,_ = train.shape
    y = train.DiagPeriodL90D
    n_splits =5
    folds = StratifiedKFold(n_splits = n_splits)
In [ ]:
cat_params = {'iterations': 882, 'learning_rate': 0.057616837575731765, 'depth': 6}
cat_params ={'iterations': 812, 'learning_rate': 0.07624501613186423, 'depth': 4}
cat_params ={'iterations': 477, 'learning_rate': 0.08666456516942729, 'depth': 4}
In [ ]:
train_copy2 = train_copy.drop('breast_cancer_diagnosis_code' ,axis=1)
test_copy2 = test_copy.drop('breast_cancer_diagnosis_code' ,axis=1)
In [ ]:
oof = train_copy[['DiagPeriodL90D']]
folds = Stock.folds
preds1=[]
log = []
stock_xtest = list()
TEST= test_copy
stock_index= []

misclassified_indices_per_fold = []
X= train_copy.drop('DiagPeriodL90D' , axis=1)
y = train_copy.DiagPeriodL90D


for j,targ in enumerate(['DiagPeriodL90D']) : 
#     y = train[targ]
    print(50*'--')
    print(f'Training k-Fold Model for Target {targ}')
    print(50*'--')
    for i,( train_index, test_index) in enumerate(folds.split(X, y)):

        print(50*'--')
        print(f'Fold {i+1}/{5}')
        print(50*'--')
        
        X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]
#   class_weights = {0: 0.7 , 1 : 0.3} ,          
      # Train model
#         stock_index.append(X_test.index)
        cat = CatBoostClassifier(**cat_params, random_seed=42 ,early_stopping_rounds=100, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,
                           
                                 logging_level='Silent' 
)
                             
                              
                                 
                                 
                                     
                                 
                                 
                                 
        cat.fit(X_train,y_train,eval_set=[(X_train,y_train),(X_test, y_test)] ,  plot=True)
        calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        calibrated_classifier.fit(X_train,y_train)
        
#         calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        # Fold Evaluation
        
#         calibrated_classifier.fit(X_train, y_train)
#         fold_pred   = model.predict_proba(X_test)
        print(50*'**')
        y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
        y_pred = calibrated_classifier.predict(X_test )
#         y_pred = [1 if i >0.78 else 0 for i in y_pred_prob ]
        print(y_pred_prob , calibrated_classifier.predict_proba(X_test)[:, 1])
        accuracy = accuracy_score(y_test, y_pred)
        
#         y_pred = [1 if i >0.55 else 0 for i in y_pred_prob ]
        roc_auc = roc_auc_score(y_test, y_pred_prob)
        conf_matrix = confusion_matrix(y_test, y_pred)
        loss = roc_auc

        print(f'Accuracy: {accuracy:.4f}')
        print(f'ROC AUC: {roc_auc:.4f}')

        print('\nClassification Report:')
        print(classification_report(y_test, y_pred))
        print(f"log_loss validation Fold {i+1}/{5} is   : {loss}" )
        log.append(loss)    
        print(50*'**')
        #update oof
        

        # Test Evaluation
        
        test_proba = calibrated_classifier.predict_proba(TEST)

        preds1.append(test_proba)
        
        
        



            
            
        conf_mat  = confusion_matrix(y_test, y_pred) 
        plt.figure(figsize=(8, 6))
        sns.set(font_scale=1.2)
        sns.set_style("whitegrid", {"axes.edgecolor": ".6", "grid.color": ".6"})

        cmap = sns.color_palette("viridis", as_cmap=True)
        heatmap = sns.heatmap(conf_matrix, annot=True, fmt='d', cmap=cmap, annot_kws={'size': 14}, cbar=False)

        heatmap.set_title('Confusion Matrix', fontdict={'fontsize': 16})
        heatmap.set_xlabel('Predicted', fontdict={'fontsize': 14})
        heatmap.set_ylabel('True', fontdict={'fontsize': 14})
        
        
        
        fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
        roc_auc = auc(fpr, tpr)

        fig = go.Figure()
        fig.add_trace(go.Scatter(x=fpr, y=tpr, mode='lines', 
                                 line=dict(color='#FF4505', width=5),
                                 name=f'AUC = {roc_auc:.2f}'))

        fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', 
                                 line=dict(color='navy', width=2, dash='dash'),
                                 name='Random'))

        fig.update_layout(
            title='ROC Curve',
            xaxis=dict(title='False Positive Rate'),
            yaxis=dict(title='True Positive Rate'),
            legend=dict(x=0.02, y=0.98),
            width=800, height=800
        )

        fig.show()
        
        threshold = 0.5
        y_pred_binary = (y_pred_prob > threshold).astype(int)
        misclassified_indices = np.where(y_pred_binary != y_test)[0]
        misclassified_indices_per_fold.append(misclassified_indices)
        stock_index.append(X_test.index)
        
        stock_xtest.append(calibrated_classifier.predict_proba(X_test))
        
plt.show()
print(50*'##')
print(f"The overall loss is {np.array(log).mean()}")



all_misclassified_indices = np.concatenate(misclassified_indices_per_fold)

print("Indices of misclassified instances:")
print(all_misclassified_indices) 
In [ ]:
0.8072683562110157 gives 0.808
In [ ]:
len(pred_probs)
In [ ]:
len(train.iloc[stock_index[1]].DiagPeriodL90D.values)
In [ ]:
#########################################
In [ ]:
import cleanlab
import sklearn
from cleanlab import Datalab
In [ ]:
X_train = train_copy.drop('DiagPeriodL90D',axis=1)
noisy_labels = train_copy.DiagPeriodL90D
data = {"X": X_train.values, "y": noisy_labels.values}
In [ ]:
labels = noisy_labels.values
In [ ]:
pred_probs = stock_xtest[1]
In [ ]:
from cleanlab.filter import find_label_issues
In [ ]:
lab = Datalab(data, label_name="y")
lab.find_issues(pred_probs=pred_probs, features=data["X"])
In [ ]:
ranked_label_issues = find_label_issues(
    labels=train.iloc[stock_index[1]].DiagPeriodL90D.values, pred_probs=pred_probs, return_indices_ranked_by="self_confidence"
)

print(f"Cleanlab found {len(ranked_label_issues)} potential label errors.")
In [ ]:
ranked_label_issues
In [ ]:
train_copy.loc[ranked_label_issues[420:], 'DiagPeriodL90D'] = train_copy.loc[ranked_label_issues[420:], 'DiagPeriodL90D'].apply(lambda x: 1 if x == 0 else 0)
In [ ]:
from scipy.stats import boxcox
In [ ]:
train_copy2 = train_copy.copy(deep =True)
test_copy2 = test_copy.copy(deep =True)
In [ ]:
import featuretools as ft
import pandas as pd

# Assuming you have a DataFrame named 'train_copy' with the default index
# If you want to use the default integer-based index as the entity index

# Create an entity set
es = ft.EntitySet(id="my_entity_set")

# Adding the entire DataFrame as an entity with the default index
es = es.add_dataframe(
    dataframe_name="ok",
    dataframe=train_copy,
    make_index=True,  # Use the default integer-based index as the entity index
)

# Define the target entity and the aggregation primitives to use
target_entity = "ok"
agg_primitives = ["sum", "mean", "max", "min", "count", "std"]

# Run deep feature synthesis to create new features
feature_matrix, feature_defs = ft.dfs(
    entityset=es,
    target_dataframe_name=target_entity,
    agg_primitives=agg_primitives,
    trans_primitives=[],
    verbose=True,
)

# Display the generated feature matrix
print(feature_matrix.head())
In [ ]:
feature_matrix, features_defs = ft.dfs(entityset=es, target_dataframe_name="DiagPeriodL90D")
In [ ]:
feature_matrix.shape
In [ ]:
import featuretools as ft

# Create an entity set
es = ft.EntitySet(id="my_entity_set")

# Adding the entire DataFrame as an entity
es = es.add_dataframe(
    dataframe_name="ok",
    dataframe=train_copy,
    index="index",  # Replace with your index column name
)

# Define the target entity and the aggregation primitives to use
target_entity = "ok"  # Update this to match the dataframe_name you added to the entity set
agg_primitives = ["sum", "mean", "max", "min", "count", "std"]

# Run deep feature synthesis to create new features
feature_matrix, feature_defs = ft.dfs(
    entityset=es,
    target_dataframe_name=target_entity,
    agg_primitives=agg_primitives,
    trans_primitives=[],
    verbose=True,
)

# Display the generated feature matrix
print(feature_matrix.head())
In [ ]:
es.plot()
In [ ]:
feature_defs
In [ ]:
import featuretools as ft
es = ft.demo.load_mock_customer(return_entityset=True)
es.plot()
In [ ]:
oof = train_copy[['DiagPeriodL90D']]
folds = Stock.folds
preds1=[]
log = []
stock_xtest = list()
TEST= test_copy
stock_index= []

misclassified_indices_per_fold = []
X= train_copy.drop('DiagPeriodL90D' , axis=1)
y = train_copy.DiagPeriodL90D


for j,targ in enumerate(['DiagPeriodL90D']) : 
#     y = train[targ]
    print(50*'--')
    print(f'Training k-Fold Model for Target {targ}')
    print(50*'--')
    for i,( train_index, test_index) in enumerate(folds.split(X, y)):

        print(50*'--')
        print(f'Fold {i+1}/{5}')
        print(50*'--')
        
        X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]
#   class_weights = {0: 0.7 , 1 : 0.3} ,          
      # Train model
#         stock_index.append(X_test.index)
        cat = CatBoostClassifier(**cat_params, random_seed=42 ,early_stopping_rounds=100, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,
                           
                                 logging_level='Silent' 
)
                             
                              
                                 
                                 
                                     
                                 
                                 
                                 
        cat.fit(X_train,y_train,eval_set=[(X_train,y_train),(X_test, y_test)] ,  plot=True)
        calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        calibrated_classifier.fit(X_train,y_train)
        
#         calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        # Fold Evaluation
        
#         calibrated_classifier.fit(X_train, y_train)
#         fold_pred   = model.predict_proba(X_test)
        print(50*'**')
        y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
        y_pred = calibrated_classifier.predict(X_test )
#         y_pred = [1 if i >0.78 else 0 for i in y_pred_prob ]
        print(y_pred_prob , calibrated_classifier.predict_proba(X_test)[:, 1])
        accuracy = accuracy_score(y_test, y_pred)
        
#         y_pred = [1 if i >0.55 else 0 for i in y_pred_prob ]
        roc_auc = roc_auc_score(y_test, y_pred_prob)
        conf_matrix = confusion_matrix(y_test, y_pred)
        loss = roc_auc

        print(f'Accuracy: {accuracy:.4f}')
        print(f'ROC AUC: {roc_auc:.4f}')

        print('\nClassification Report:')
        print(classification_report(y_test, y_pred))
        print(f"log_loss validation Fold {i+1}/{5} is   : {loss}" )
        log.append(loss)    
        print(50*'**')
        #update oof
        

        # Test Evaluation
        
        test_proba = calibrated_classifier.predict_proba(TEST)

        preds1.append(test_proba)
        
        
        



            
            
        conf_mat  = confusion_matrix(y_test, y_pred) 
        plt.figure(figsize=(8, 6))
        sns.set(font_scale=1.2)
        sns.set_style("whitegrid", {"axes.edgecolor": ".6", "grid.color": ".6"})

        cmap = sns.color_palette("viridis", as_cmap=True)
        heatmap = sns.heatmap(conf_matrix, annot=True, fmt='d', cmap=cmap, annot_kws={'size': 14}, cbar=False)

        heatmap.set_title('Confusion Matrix', fontdict={'fontsize': 16})
        heatmap.set_xlabel('Predicted', fontdict={'fontsize': 14})
        heatmap.set_ylabel('True', fontdict={'fontsize': 14})
        
        
        
        fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
        roc_auc = auc(fpr, tpr)

        fig = go.Figure()
        fig.add_trace(go.Scatter(x=fpr, y=tpr, mode='lines', 
                                 line=dict(color='#FF4505', width=5),
                                 name=f'AUC = {roc_auc:.2f}'))

        fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', 
                                 line=dict(color='navy', width=2, dash='dash'),
                                 name='Random'))

        fig.update_layout(
            title='ROC Curve',
            xaxis=dict(title='False Positive Rate'),
            yaxis=dict(title='True Positive Rate'),
            legend=dict(x=0.02, y=0.98),
            width=800, height=800
        )

        fig.show()
        
        threshold = 0.5
        y_pred_binary = (y_pred_prob > threshold).astype(int)
        misclassified_indices = np.where(y_pred_binary != y_test)[0]
        misclassified_indices_per_fold.append(misclassified_indices)
        stock_index.append(X_test.index)
        
        stock_xtest.append(calibrated_classifier.predict_proba(X_test))
        
plt.show()
print(50*'##')
print(f"The overall loss is {np.array(log).mean()}")



all_misclassified_indices = np.concatenate(misclassified_indices_per_fold)

print("Indices of misclassified instances:")
print(all_misclassified_indices) 
In [ ]:
lab.find_issues(pred_probs=pred_probs, features=data["X"])
In [ ]:
The overall loss is 0.8072683562110157
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
cat = CatBoostClassifier(**cat_params, random_seed=42 ,early_stopping_rounds=100, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,
                           
                                 logging_level='Silent' 
)
In [ ]:
cl = cleanlab.classification.CleanLearning(cat)
data = train_copy.drop('DiagPeriodL90D',axis=1)
labels = train_copy.DiagPeriodL90D
# cleanlab finds data and label issues in **any dataset**... in ONE line of code!
label_issues = cl.find_label_issues(data, labels)

# cleanlab trains a robust version of your model that works more reliably with noisy data.
cl.fit(data, labels)

# cleanlab estimates the predictions you would have gotten if you had trained with *no* label issues.
cl.predict(data)

# A universal data-centric AI tool, cleanlab quantifies class-level issues and overall data quality, for any dataset.
cleanlab.dataset.health_summary(labels, confident_joint=cl.confident_joint)
In [ ]:
cleanlab.dataset.health_summary(labels, confident_joint=cl.confident_joint)
In [ ]:
pr =cl.predict(data)
In [ ]:
differs = 0
for i in range(len(pr)) :
    if pr[i] != train_copy.DiagPeriodL90D.values[i] : 
        differs+=1
               
In [ ]:
differs
In [ ]:
train_cop = train_copy.copy(deep =True)
In [ ]:
train_cop['DiagPeriodL90D'] = pr
In [ ]:
oof = train_cop[['DiagPeriodL90D']]
folds = Stock.folds
preds1=[]
log = []

TEST= test_copy
stock_index= []

misclassified_indices_per_fold = []
X= train_cop.drop('DiagPeriodL90D' , axis=1)
y = train_cop.DiagPeriodL90D


for j,targ in enumerate(['DiagPeriodL90D']) : 
#     y = train[targ]
    print(50*'--')
    print(f'Training k-Fold Model for Target {targ}')
    print(50*'--')
    for i,( train_index, test_index) in enumerate(folds.split(X, y)):

        print(50*'--')
        print(f'Fold {i+1}/{5}')
        print(50*'--')
        
        X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]
#   class_weights = {0: 0.7 , 1 : 0.3} ,          
      # Train model
#         stock_index.append(X_test.index)
        cat = CatBoostClassifier(**cat_params, random_seed=42 ,early_stopping_rounds=100, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,
                           
                                 logging_level='Silent' 
)
                             
                              
                                 
                                 
                                     
                                 
                                 
                                 
        cat.fit(X_train,y_train,eval_set=[(X_train,y_train),(X_test, y_test)] ,  plot=True)
        calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        calibrated_classifier.fit(X_train,y_train)
        
#         calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        # Fold Evaluation
        
#         calibrated_classifier.fit(X_train, y_train)
#         fold_pred   = model.predict_proba(X_test)
        print(50*'**')
        y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
        y_pred = calibrated_classifier.predict(X_test )
#         y_pred = [1 if i >0.78 else 0 for i in y_pred_prob ]
        print(y_pred_prob , calibrated_classifier.predict_proba(X_test)[:, 1])
        accuracy = accuracy_score(y_test, y_pred)
        
#         y_pred = [1 if i >0.55 else 0 for i in y_pred_prob ]
        roc_auc = roc_auc_score(y_test, y_pred_prob)
        conf_matrix = confusion_matrix(y_test, y_pred)
        loss = roc_auc

        print(f'Accuracy: {accuracy:.4f}')
        print(f'ROC AUC: {roc_auc:.4f}')

        print('\nClassification Report:')
        print(classification_report(y_test, y_pred))
        print(f"log_loss validation Fold {i+1}/{5} is   : {loss}" )
        log.append(loss)    
        print(50*'**')
        #update oof
        

        # Test Evaluation
        
        test_proba = calibrated_classifier.predict_proba(TEST)

        preds1.append(test_proba)
        
        
        



            
            
        conf_mat  = confusion_matrix(y_test, y_pred) 
        plt.figure(figsize=(8, 6))
        sns.set(font_scale=1.2)
        sns.set_style("whitegrid", {"axes.edgecolor": ".6", "grid.color": ".6"})

        cmap = sns.color_palette("viridis", as_cmap=True)
        heatmap = sns.heatmap(conf_matrix, annot=True, fmt='d', cmap=cmap, annot_kws={'size': 14}, cbar=False)

        heatmap.set_title('Confusion Matrix', fontdict={'fontsize': 16})
        heatmap.set_xlabel('Predicted', fontdict={'fontsize': 14})
        heatmap.set_ylabel('True', fontdict={'fontsize': 14})
        
        
        
        fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
        roc_auc = auc(fpr, tpr)

        fig = go.Figure()
        fig.add_trace(go.Scatter(x=fpr, y=tpr, mode='lines', 
                                 line=dict(color='#FF4505', width=5),
                                 name=f'AUC = {roc_auc:.2f}'))

        fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', 
                                 line=dict(color='navy', width=2, dash='dash'),
                                 name='Random'))

        fig.update_layout(
            title='ROC Curve',
            xaxis=dict(title='False Positive Rate'),
            yaxis=dict(title='True Positive Rate'),
            legend=dict(x=0.02, y=0.98),
            width=800, height=800
        )

        fig.show()
        
        threshold = 0.5
        y_pred_binary = (y_pred_prob > threshold).astype(int)
        misclassified_indices = np.where(y_pred_binary != y_test)[0]
        misclassified_indices_per_fold.append(misclassified_indices)
        stock_index.append(X_test.index)

plt.show()
print(50*'##')
print(f"The overall loss is {np.array(log).mean()}")



all_misclassified_indices = np.concatenate(misclassified_indices_per_fold)

print("Indices of misclassified instances:")
print(all_misclassified_indices) 
In [ ]:
plt.figure(figsize=(10,4))
sns.histplot(np.mean(preds1 , 0)[:,1])
plt.title("Distribution of final predictions")
plt.show()
In [ ]:
preds1
In [ ]:
clf = CatBoostClassifier(**cat_params, random_seed=42 ,early_stopping_rounds=100, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,
                           
                                 logging_level='Silent' 
)
In [ ]:
from sklearn.model_selection import cross_val_predict
In [ ]:
num_crossval_folds = 5
pred_probs = cross_val_predict(
    clf,
    X_processed,
    labels,
    cv=num_crossval_folds,
    method="predict_proba",
)
In [ ]:
numerical_features = train_copy.select_dtypes(include=['number']).columns
binary_features = [col for col in train_copy.columns if train_copy[col].nunique() == 2]

# Get numerical features that are not binary
non_binary_numerical_features = [col for col in numerical_features if col not in binary_features]
In [ ]:
scaler = StandardScaler()
In [ ]:
train_copy2 = train_copy.copy(deep =True)
test_copy2 = test_copy.copy(deep = True)
In [ ]:
train_copy2[non_binary_numerical_features] = scaler.fit_transform(train_copy2[non_binary_numerical_features])
test_copy2[non_binary_numerical_features] = scaler.transform(test_copy2[non_binary_numerical_features])
In [ ]:
oof = train_copy2[['DiagPeriodL90D']]
folds = Stock.folds
preds1=[]
log = []

TEST= test_copy2
stock_index= []

misclassified_indices_per_fold = []
X= train_copy2.drop('DiagPeriodL90D' , axis=1)
y = train_copy2.DiagPeriodL90D


for j,targ in enumerate(['DiagPeriodL90D']) : 
#     y = train[targ]
    print(50*'--')
    print(f'Training k-Fold Model for Target {targ}')
    print(50*'--')
    for i,( train_index, test_index) in enumerate(folds.split(X, y)):

        print(50*'--')
        print(f'Fold {i+1}/{5}')
        print(50*'--')
        
        X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]
#   class_weights = {0: 0.7 , 1 : 0.3} ,          
      # Train model
#         stock_index.append(X_test.index)
        cat = CatBoostClassifier(**cat_params, random_seed=42 ,early_stopping_rounds=100, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,
                           
                                 logging_level='Silent' 
)
                             
                              
                                 
                                 
                                     
                                 
                                 
                                 
        cat.fit(X_train,y_train,eval_set=[(X_train,y_train),(X_test, y_test)] ,  plot=True)
        calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        calibrated_classifier.fit(X_train,y_train)
        
#         calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        # Fold Evaluation
        
#         calibrated_classifier.fit(X_train, y_train)
#         fold_pred   = model.predict_proba(X_test)
        print(50*'**')
        y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
        y_pred = calibrated_classifier.predict(X_test )
#         y_pred = [1 if i >0.78 else 0 for i in y_pred_prob ]
        print(y_pred_prob , calibrated_classifier.predict_proba(X_test)[:, 1])
        accuracy = accuracy_score(y_test, y_pred)
        
#         y_pred = [1 if i >0.55 else 0 for i in y_pred_prob ]
        roc_auc = roc_auc_score(y_test, y_pred_prob)
        conf_matrix = confusion_matrix(y_test, y_pred)
        loss = roc_auc

        print(f'Accuracy: {accuracy:.4f}')
        print(f'ROC AUC: {roc_auc:.4f}')

        print('\nClassification Report:')
        print(classification_report(y_test, y_pred))
        print(f"log_loss validation Fold {i+1}/{5} is   : {loss}" )
        log.append(loss)    
        print(50*'**')
        #update oof
        

        # Test Evaluation
        
        test_proba = calibrated_classifier.predict_proba(TEST)

        preds1.append(test_proba)
        
        
        



            
            
        conf_mat  = confusion_matrix(y_test, y_pred) 
        plt.figure(figsize=(8, 6))
        sns.set(font_scale=1.2)
        sns.set_style("whitegrid", {"axes.edgecolor": ".6", "grid.color": ".6"})

        cmap = sns.color_palette("viridis", as_cmap=True)
        heatmap = sns.heatmap(conf_matrix, annot=True, fmt='d', cmap=cmap, annot_kws={'size': 14}, cbar=False)

        heatmap.set_title('Confusion Matrix', fontdict={'fontsize': 16})
        heatmap.set_xlabel('Predicted', fontdict={'fontsize': 14})
        heatmap.set_ylabel('True', fontdict={'fontsize': 14})
        
        
        
        fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
        roc_auc = auc(fpr, tpr)

        fig = go.Figure()
        fig.add_trace(go.Scatter(x=fpr, y=tpr, mode='lines', 
                                 line=dict(color='#FF4505', width=5),
                                 name=f'AUC = {roc_auc:.2f}'))

        fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', 
                                 line=dict(color='navy', width=2, dash='dash'),
                                 name='Random'))

        fig.update_layout(
            title='ROC Curve',
            xaxis=dict(title='False Positive Rate'),
            yaxis=dict(title='True Positive Rate'),
            legend=dict(x=0.02, y=0.98),
            width=800, height=800
        )

        fig.show()
        
        threshold = 0.5
        y_pred_binary = (y_pred_prob > threshold).astype(int)
        misclassified_indices = np.where(y_pred_binary != y_test)[0]
        misclassified_indices_per_fold.append(misclassified_indices)
        stock_index.append(X_test.index)

plt.show()
print(50*'##')
print(f"The overall loss is {np.array(log).mean()}")



all_misclassified_indices = np.concatenate(misclassified_indices_per_fold)

print("Indices of misclassified instances:")
print(all_misclassified_indices) 
In [ ]:
X_processed = train_copy2.drop('DiagPeriodL90D' ,axis=1)
In [ ]:
from sklearn.neighbors import NearestNeighbors
from cleanlab import Datalab
In [ ]:
!pip install 'cleanlab[datalab]'
In [ ]:
data = {"X": X_processed.values, "y": train_copy2.DiagPeriodL90D}

lab = Datalab(data, label_name="y")
lab.find_issues(pred_probs=pred_probs)
In [ ]:
from cleanlab.filter import find_label_issues
In [ ]:
train_data = train_copy.drop('breast_cancer_diagnosis_desc' ,axis=1 )
train_labels = train_copy.breast_cancer_diagnosis_desc
In [ ]:
model = CatBoostClassifier(**cat_params, random_seed=42 ,early_stopping_rounds=100, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,
                           
                                 logging_level='Silent' )
In [ ]:
pip install utils
In [ ]:
import utils
In [ ]:
from cleanlab.multiannotator import get_majority_vote_label, get_label_quality_multiannotator, get_active_learning_scores

from utils.model_training import fit_predict_proba
from utils.active_learning import setup_next_iter_data, add_new_annotator
In [ ]:
pred_probs = cross_val_predict(model, train_data, train_labels, method='predict_proba')
In [ ]:
issue_idx = find_label_issues(train_copy.DiagPeriodL90D, np.mean(preds1 , 0)[:,1], return_indices_ranked_by='self_confidence')
In [ ]:
 
In [ ]:
 
In [ ]:
train_copy.DiagPeriodL90D
In [ ]:
0.8072683562110157 => 0.808 1 4 6 7 13 16 18
In [ ]:
import numpy as np
import pandas as pd
from sklearn.ensemble import ExtraTreesClassifier
import matplotlib.pyplot as plt

from cleanlab.multiannotator import get_majority_vote_label, get_label_quality_multiannotator, get_active_learning_scores

from utils.model_training import fit_predict_proba
from utils.active_learning import setup_next_iter_data, add_new_annotator
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
sum = 0
count = 0
In [ ]:
set(list(range(20))) - set([1,4 ,6 ,7 ,13 ,16 ,18])
In [ ]:
for i in set(list(range(20))) - set([1,4 ,6 ,7 ,13 ,16 ,18]) : 
    count+=1
    sum = sum + preds1[i]
In [ ]:
result = sum/count
In [ ]:
plot_features = pd.DataFrame()
plot_features['features'] = cat.feature_names_
plot_features['features_importance'] = cat.feature_importances_
n_top_feats = 40
plt.figure(figsize=(16, 16))
sns.barplot(data=plot_features.sort_values(by='features_importance', ascending=False).head(n_top_feats), x='features_importance', y='features');
plt.title(f'{n_top_feats} TOP feature importance');
In [ ]:
plt.figure(figsize=(10,4))
sns.histplot(np.mean(preds1 , 0)[:,1])
plt.title("Distribution of final predictions")
plt.show()
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
X= train_copy.drop('DiagPeriodL90D' , axis=1)
y = train_copy.DiagPeriodL90D
X_train , X_test , y_train , y_test  = train_test_split(X, y ,test_size= 0.2)
def objective(trial):
    # Define hyperparameters to be optimized
    cat_params = {
        'iterations': trial.suggest_int('iterations', 50, 1000),
        'learning_rate': trial.suggest_float('learning_rate', 0.001, 0.1),
        'depth': trial.suggest_int('depth', 4, 10),
#         'class_weights': {0: trial.suggest_float('class_weight_0', 0.1, 0.9), 1: 1.0},
      
 
        # Add other hyperparameters you want to optimize
    }

    # Initialize lists to store results for each fold
    auc_scores = []

    for i, (train_index, test_index) in enumerate(folds.split(X, y)):
        X_fold_train, X_fold_test = X.iloc[train_index], X.iloc[test_index]
        y_fold_train, y_fold_test = y.iloc[train_index], y.iloc[test_index]

        # Train model
        cat = CatBoostClassifier(**cat_params, random_seed=42 ,early_stopping_rounds=100, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,
                                 bootstrap_type= "Bayesian" ,
                                  
                                 logging_level='Silent'   ) 
        cat.fit(X_fold_train, y_fold_train, eval_set=[(X_fold_train, y_fold_train), (X_fold_test, y_fold_test)])

        # Evaluate model on the fold
        y_pred_prob = cat.predict_proba(X_fold_test)[:, 1]
        auc = roc_auc_score(y_fold_test, y_pred_prob)
        auc_scores.append(auc)

    # Compute mean AUC across folds
    mean_auc = np.mean(auc_scores)

    # Return the negative mean AUC since Optuna aims to minimize the objective
    return mean_auc

# Create an Optuna study and run the optimization
study = optuna.create_study(direction='maximize')
study.optimize(objective, n_trials=100 , show_progress_bar= True  )  # You can adjust the number of trials

# Get the best hyperparameters
best_params = study.best_params
In [ ]:
best_params
In [ ]:
cat_bayesian = {'iterations': 871, 'learning_rate': 0.09173834851423435, 'depth': 5}
In [ ]:
oof = train_copy[['DiagPeriodL90D']]
folds = Stock.folds
preds2=[]
log = []
X= train_copy.drop('DiagPeriodL90D' , axis=1)

TEST= test_copy
stock_index= []

misclassified_indices_per_fold = []

y = train_copy.DiagPeriodL90D


for j,targ in enumerate(['DiagPeriodL90D']) : 
#     y = train[targ]
    print(50*'--')
    print(f'Training k-Fold Model for Target {targ}')
    print(50*'--')
    for i,( train_index, test_index) in enumerate(folds.split(X, y)):

        print(50*'--')
        print(f'Fold {i+1}/{5}')
        print(50*'--')
        
        X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]
#   class_weights = {0: 0.7 , 1 : 0.3} ,          
      # Train model
#         stock_index.append(X_test.index)
        cat = CatBoostClassifier(**cat_bayesian, random_seed=42 ,early_stopping_rounds=100, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,bootstrap_type= "Bayesian",
                           
                                 logging_level='Silent' 
)
                             
                              
                                 
                                 
                                     
                                 
                                 
                                 
        cat.fit(X_train,y_train,eval_set=[(X_train,y_train),(X_test, y_test)] ,  plot=True)
        calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        calibrated_classifier.fit(X_train,y_train)
        
#         calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        # Fold Evaluation
        
#         calibrated_classifier.fit(X_train, y_train)
#         fold_pred   = model.predict_proba(X_test)
        print(50*'**')
        y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
        y_pred = calibrated_classifier.predict(X_test )
#         y_pred = [1 if i >0.78 else 0 for i in y_pred_prob ]
        print(y_pred_prob , calibrated_classifier.predict_proba(X_test)[:, 1])
        accuracy = accuracy_score(y_test, y_pred)
        
#         y_pred = [1 if i >0.55 else 0 for i in y_pred_prob ]
        roc_auc = roc_auc_score(y_test, y_pred_prob)
        conf_matrix = confusion_matrix(y_test, y_pred)
        loss = roc_auc

        print(f'Accuracy: {accuracy:.4f}')
        print(f'ROC AUC: {roc_auc:.4f}')

        print('\nClassification Report:')
        print(classification_report(y_test, y_pred))
        print(f"log_loss validation Fold {i+1}/{5} is   : {loss}" )
        log.append(loss)    
        print(50*'**')
        #update oof
        

        # Test Evaluation
        
        test_proba = calibrated_classifier.predict_proba(TEST)

        preds2.append(test_proba)
        
        
        



            
            
        conf_mat  = confusion_matrix(y_test, y_pred) 
        plt.figure(figsize=(8, 6))
        sns.set(font_scale=1.2)
        sns.set_style("whitegrid", {"axes.edgecolor": ".6", "grid.color": ".6"})

        cmap = sns.color_palette("viridis", as_cmap=True)
        heatmap = sns.heatmap(conf_matrix, annot=True, fmt='d', cmap=cmap, annot_kws={'size': 14}, cbar=False)

        heatmap.set_title('Confusion Matrix', fontdict={'fontsize': 16})
        heatmap.set_xlabel('Predicted', fontdict={'fontsize': 14})
        heatmap.set_ylabel('True', fontdict={'fontsize': 14})
        
        
        
        fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
        roc_auc = auc(fpr, tpr)

        fig = go.Figure()
        fig.add_trace(go.Scatter(x=fpr, y=tpr, mode='lines', 
                                 line=dict(color='#FF4505', width=5),
                                 name=f'AUC = {roc_auc:.2f}'))

        fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', 
                                 line=dict(color='navy', width=2, dash='dash'),
                                 name='Random'))

        fig.update_layout(
            title='ROC Curve',
            xaxis=dict(title='False Positive Rate'),
            yaxis=dict(title='True Positive Rate'),
            legend=dict(x=0.02, y=0.98),
            width=800, height=800
        )

        fig.show()
        
        threshold = 0.5
        y_pred_binary = (y_pred_prob > threshold).astype(int)
        misclassified_indices = np.where(y_pred_binary != y_test)[0]
        misclassified_indices_per_fold.append(misclassified_indices)
        stock_index.append(X_test.index)

plt.show()
print(50*'##')
print(f"The overall loss is {np.array(log).mean()}")



all_misclassified_indices = np.concatenate(misclassified_indices_per_fold)

print("Indices of misclassified instances:")
print(all_misclassified_indices) 
In [ ]:
plt.figure(figsize=(10,4))
sns.histplot(np.mean(preds1 , 0)[:,1])
plt.title("Distribution of final predictions")
plt.show()
In [ ]:
X= train_copy.drop('DiagPeriodL90D' , axis=1)
y = train_copy.DiagPeriodL90D
X_train , X_test , y_train , y_test  = train_test_split(X, y ,test_size= 0.2)
def objective(trial):
    # Define hyperparameters to be optimized
    cat_params = {
        'iterations': trial.suggest_int('iterations', 50, 1000),
        'learning_rate': trial.suggest_float('learning_rate', 0.001, 0.1),
        'depth': trial.suggest_int('depth', 4, 10),
#         'class_weights': {0: trial.suggest_float('class_weight_0', 0.1, 0.9), 1: 1.0},
      
 
        # Add other hyperparameters you want to optimize
    }

    # Initialize lists to store results for each fold
    auc_scores = []

    for i, (train_index, test_index) in enumerate(folds.split(X, y)):
        X_fold_train, X_fold_test = X.iloc[train_index], X.iloc[test_index]
        y_fold_train, y_fold_test = y.iloc[train_index], y.iloc[test_index]

        # Train model
        cat = CatBoostClassifier(**cat_params, random_seed=42 ,early_stopping_rounds=100, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,
                                 bootstrap_type= "Bernoulli" ,
                                  
                                 logging_level='Silent'   ) 
        cat.fit(X_fold_train, y_fold_train, eval_set=[(X_fold_train, y_fold_train), (X_fold_test, y_fold_test)])

        # Evaluate model on the fold
        y_pred_prob = cat.predict_proba(X_fold_test)[:, 1]
        auc = roc_auc_score(y_fold_test, y_pred_prob)
        auc_scores.append(auc)

    # Compute mean AUC across folds
    mean_auc = np.mean(auc_scores)

    # Return the negative mean AUC since Optuna aims to minimize the objective
    return mean_auc

# Create an Optuna study and run the optimization
study = optuna.create_study(direction='maximize')
study.optimize(objective, n_trials=100 , show_progress_bar= True  )  # You can adjust the number of trials

# Get the best hyperparameters
best_params = study.best_params
In [ ]:
best_params
In [ ]:
cat_Bernoulli = {'iterations': 699, 'learning_rate': 0.06564484097584186, 'depth': 4}
In [ ]:
oof = train_copy[['DiagPeriodL90D']]
folds = Stock.folds
preds3=[]
log = []
X= train_copy.drop('DiagPeriodL90D' , axis=1)

TEST= test_copy
stock_index= []

misclassified_indices_per_fold = []

y = train_copy.DiagPeriodL90D


for j,targ in enumerate(['DiagPeriodL90D']) : 
#     y = train[targ]
    print(50*'--')
    print(f'Training k-Fold Model for Target {targ}')
    print(50*'--')
    for i,( train_index, test_index) in enumerate(folds.split(X, y)):

        print(50*'--')
        print(f'Fold {i+1}/{5}')
        print(50*'--')
        
        X_train, X_test, y_train, y_test = X.iloc[train_index], X.iloc[test_index], y.iloc[train_index], y.iloc[test_index]
#   class_weights = {0: 0.7 , 1 : 0.3} ,          
      # Train model
#         stock_index.append(X_test.index)
        cat = CatBoostClassifier(**cat_Bernoulli, random_seed=42 ,early_stopping_rounds=100, cat_features = [i for i in train_copy.columns if train_copy[i].dtype == 'object']+["patient_zip3"], 
                                 loss_function = "Logloss" ,use_best_model=True , eval_metric="AUC" , 
                                text_features = ['breast_cancer_diagnosis_desc'] ,bootstrap_type= "Bernoulli",
                           
                                 logging_level='Silent' 
)
                             
                              
                                 
                                 
                                     
                                 
                                 
                                 
        cat.fit(X_train,y_train,eval_set=[(X_train,y_train),(X_test, y_test)] ,  plot=True)
        calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        calibrated_classifier.fit(X_train,y_train)
        
#         calibrated_classifier = CalibratedClassifierCV(cat, method='sigmoid', cv='prefit' ) 
        # Fold Evaluation
        
#         calibrated_classifier.fit(X_train, y_train)
#         fold_pred   = model.predict_proba(X_test)
        print(50*'**')
        y_pred_prob = calibrated_classifier.predict_proba(X_test)[:, 1]
        y_pred = calibrated_classifier.predict(X_test )
#         y_pred = [1 if i >0.78 else 0 for i in y_pred_prob ]
        print(y_pred_prob , calibrated_classifier.predict_proba(X_test)[:, 1])
        accuracy = accuracy_score(y_test, y_pred)
        
#         y_pred = [1 if i >0.55 else 0 for i in y_pred_prob ]
        roc_auc = roc_auc_score(y_test, y_pred_prob)
        conf_matrix = confusion_matrix(y_test, y_pred)
        loss = roc_auc

        print(f'Accuracy: {accuracy:.4f}')
        print(f'ROC AUC: {roc_auc:.4f}')

        print('\nClassification Report:')
        print(classification_report(y_test, y_pred))
        print(f"log_loss validation Fold {i+1}/{5} is   : {loss}" )
        log.append(loss)    
        print(50*'**')
        #update oof
        

        # Test Evaluation
        
        test_proba = calibrated_classifier.predict_proba(TEST)

        preds3.append(test_proba)
        
        
        



            
            
        conf_mat  = confusion_matrix(y_test, y_pred) 
        plt.figure(figsize=(8, 6))
        sns.set(font_scale=1.2)
        sns.set_style("whitegrid", {"axes.edgecolor": ".6", "grid.color": ".6"})

        cmap = sns.color_palette("viridis", as_cmap=True)
        heatmap = sns.heatmap(conf_matrix, annot=True, fmt='d', cmap=cmap, annot_kws={'size': 14}, cbar=False)

        heatmap.set_title('Confusion Matrix', fontdict={'fontsize': 16})
        heatmap.set_xlabel('Predicted', fontdict={'fontsize': 14})
        heatmap.set_ylabel('True', fontdict={'fontsize': 14})
        
        
        
        fpr, tpr, _ = roc_curve(y_test, y_pred_prob)
        roc_auc = auc(fpr, tpr)

        fig = go.Figure()
        fig.add_trace(go.Scatter(x=fpr, y=tpr, mode='lines', 
                                 line=dict(color='#FF4505', width=5),
                                 name=f'AUC = {roc_auc:.2f}'))

        fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', 
                                 line=dict(color='navy', width=2, dash='dash'),
                                 name='Random'))

        fig.update_layout(
            title='ROC Curve',
            xaxis=dict(title='False Positive Rate'),
            yaxis=dict(title='True Positive Rate'),
            legend=dict(x=0.02, y=0.98),
            width=800, height=800
        )

        fig.show()
        
        threshold = 0.5
        y_pred_binary = (y_pred_prob > threshold).astype(int)
        misclassified_indices = np.where(y_pred_binary != y_test)[0]
        misclassified_indices_per_fold.append(misclassified_indices)
        stock_index.append(X_test.index)

plt.show()
print(50*'##')
print(f"The overall loss is {np.array(log).mean()}")



all_misclassified_indices = np.concatenate(misclassified_indices_per_fold)

print("Indices of misclassified instances:")
print(all_misclassified_indices) 
In [ ]:
plt.figure(figsize=(10,4))
sns.histplot(np.mean(preds1 , 0)[:,1])
plt.title("Distribution of final predictions")
plt.show()
In [ ]:
best = pd.read_csv('improve (2).csv')
In [ ]:
plt.figure(figsize=(10,4))
sns.histplot(best.DiagPeriodL90D)
plt.title("Distribution of final predictions")
plt.show()
In [ ]:
sub["DiagPeriodL90D"] = np.mean(preds1 , 0)[:,1]*0.06+best.DiagPeriodL90D*0.94
sub.to_csv('new.csv' , index = False)
In [ ]:
plt.figure(figsize=(10,4))
sns.histplot(sub.DiagPeriodL90D)
plt.title("Distribution of final predictions")
plt.show()
In [ ]:
train_copy.breast_cancer_diagnosis_desc.unique()
In [ ]:
train_copy.to_csv('cleaned_train.csv' , index= False)
test_copy.to_csv('cleaned_test.csv' , index =False)